如何从具有关系的表中检索数据 - 多对多(SQLAlchemy)?

时间:2014-05-14 12:22:48

标签: python sql sqlalchemy

我有两个具有多对多关系的模型(SQLAlchemy):

association_table = Table('association', Base.metadata,
    Column('left_id', Integer, ForeignKey('left.id')),
    Column('right_id', Integer, ForeignKey('right.id'))
)

class Parent(Base):
    __tablename__ = 'left'
    id = Column(Integer, primary_key=True)
    children = relationship("Child",
                    secondary="association",
                    backref="parents")

class Child(Base):
    __tablename__ = 'right'
    id = Column(Integer, primary_key=True)

获得“所有父母(列表中的第二位)孩子”我可以这样:

parents = session.query(Parent).filter(Parent.children.any(id=2))

如何获得“父母的所有孩子”?

1 个答案:

答案 0 :(得分:1)

以下任何一项都应该:

# 1.
children = session.query(Child).filter(Child.parents.any(Parent.id==??))
# 2.
children = session.query(Child).join(Parent, Child.parents).filter(Parent.id == 99)
# 3.
my_parent = session.query(Parent).get(2)
children = session.query(Child).with_parent(my_parent).all()
相关问题