SQLAlchemy 1.4 - How to query many-to-many relationships?

Viewed 68

I'm new to SQLAlchemy and their docs are a bit confusing but I have a bi-directional many-to-many relationship defined as so:

class Parent(Base):
    __tablename__ = 'parents'

    id = Column(Integer, autoincrement=True, primary_key=True)
    children = relationship('Child', secondary=association_table,
                         back_populates='parents')

class Child(Base):
    __tablename__ = 'children'

    id = Column(Integer, autoincrement=True, primary_key=True)
    parents = relationship(
        'Parent', secondary=association_table, back_populates='children')

association_table = Table('parent_child_association', Base.metadata,
                          Column('parent_id', ForeignKey(
                              'parents.id'), primary_key=True),
                          Column('child_id', ForeignKey(
                              'children.id'), primary_key=True)
                          )

I can't seem to figure out a way to query for Parents where it pulls all the children per parent under Parent.children array.

Some help would be greatly appreciated as I don't have too much experience with SQLAlchemy.

0 Answers
Related