与SQLAlchemy进行多对多关系遍历

时间:2014-04-02 20:15:27

标签: python database sqlalchemy

我对SQLAlchemy很新(我对数据库一般没有太多经验)。我试图遍历两个多对多的关系。鉴于父母,我怎样才能得到所有独特的孙子?

parent_child_table = Table('parent_child', Base.metadata,
    Column('parent_id', Integer, ForeignKey('parent.id')),
    Column('child_id', Integer, ForeignKey('child.id'))
)

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

child_grandchild_table = Table('child_grandchild', Base.metadata,
    Column('child_id', Integer, ForeignKey('child.id')),
    Column('grandchild_id', Integer, ForeignKey('grandchild.id'))
)

class Child(Base):
    __tablename__ = 'child'
    id = Column(Integer, primary_key=True)
    grandchildren = relationship("Grandchild",
                         secondary=child_grandchild_table,
                         backref="children")

class Grandchild(Base):
    __tablename__ = 'grandchild'
    id = Column(Integer, primary_key=True)

谢谢!这个问题让我很头疼......

1 个答案:

答案 0 :(得分:1)

最直接的方式:

# my_parent = ... (instance of Parent)

q = (session.query(Grandchild)
        .join(Child, Grandchild.children)
        .join(Parent, Child.parents)
        .filter(Parent.id == my_parent.id)
        )

sqlalchemy将仅返回唯一的Grandchild个实例(尽管SQL查询不会过滤重复项)。