如何使用子查询过滤一对多关系上的sqlalchemy查询?

时间:2015-02-09 21:53:36

标签: python sqlalchemy

所以如果我有两个sqlalchemy表,比如

class Parent
    id = Column(Integer, primary_key=True)
    children = relationship('Child', lazy='joined', backref=backref('parent', lazy='joined'))
class Child
    id = Column(Integer, primary_key=True)
    age = Column(Integer)

如何找到所有至少有一个有年龄的孩子的父母> 10?

我尝试过这样的事情,虽然这不起作用:

Session.query(Parent.id).filter(func.count(Parent.children.filter(Child.age >= 10)) > 0)

1 个答案:

答案 0 :(得分:2)

假设这个模型:

class Parent(Base):
    id = Column(Integer, primary_key=True)
    name = Column(String)
    children = relationship('Child', lazy='joined',
                            backref=backref('parent', lazy='joined'))

class Child(Base):
    id = Column(Integer, primary_key=True)
    parent_id = Column(ForeignKey(Parent.id))
    age = Column(Integer)

使用any构造来使过滤器正常工作:

q = (session.query(Parent)
     .filter(Parent.children.any(Child.age >= 10))
     )

for p in q:
    print("{}".format(p))
    for c in p.children:
        print("  {}".format(c))