[英]How to retrieve data from tables with relationships - Many To Many (SQLAlchemy)?
I have two models with a many to many relationship (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)
Get "all parents of one (second on the list) the child" I can that way: 我可以这样获得“一个孩子(列表中第二个)的所有父母”:
parents = session.query(Parent).filter(Parent.children.any(id=2))
And how to get "all the children of a parent"? 以及如何获得“父母的所有子女”?
Any of the below should do: 以下任何一项都可以:
# 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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.