所以如果我有两个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)
答案 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))