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

2 投票
1 回答
3478 浏览
提问于 2025-04-18 06:32

我有两个模型,它们之间是多对多的关系(使用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 个回答

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()

撰写回答