【问题标题】:How to retrieve data from tables with relationships - Many To Many (SQLAlchemy)?如何从具有关系的表中检索数据 - 多对多(SQLAlchemy)?
【发布时间】:2014-05-14 20:49:15
【问题描述】:

我有两个具有多对多关系的模型(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))

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

【问题讨论】:

  • 仔细阅读文档...parent = session.query(Parent).get(id=1) 然后for children in parent.children: print children

标签: python sql sqlalchemy


【解决方案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()

【讨论】:

    猜你喜欢
    • 2015-03-29
    • 1970-01-01
    • 1970-01-01
    • 2013-01-10
    • 2021-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多