我在构建查询时遇到困难,A
个对象按C
计数进行过滤,其中C
是A
的孙子。这是我目前的(简化)模型代码:
class A(Base):
__tablename__ = 'as'
pk = Column(Integer, primary_key=True)
class B(Base):
__tablename__ = 'bs'
pk = Column(Integer, primary_key=True)
a_id = Column(Integer, ForeignKey('as.pk')
a = relationship('A', backref='bees')
class C(Base):
__tablename = 'cs'
pk = Column(Integer, primary_key=True)
child_id = Column(Integer, ForeignKey('bs.id'))
child = relationship('B', backref='cees')
我尝试了以下查询,但没有成功:
DBSession.query(A).filter(func.count(A.bees.cees) == 5)
# Neither 'InstrumentedAttribute' object nor 'Comparator' object associated
# with A.bees has an attribute 'cees'
DBSession.query(A).having(B.cees == 5)
# missing FROM-clause entry for table "bs"
所有人都非常感谢。
答案 0 :(得分:1)
在subquery
:
sq = (session.query(A.pk.label('a_pk'), func.count(C.pk).label('num_cees'))
.outerjoin(B).outerjoin(C).group_by(A.pk)
.having(func.count(C.pk) == 5) # toggle-comment-line
).subquery('c_count')
q = (session.query(A)
.join(sq, A.pk == sq.c.a_pk)
# .filter(sq.c.num_cees == 5) # toggle-comment-line
)
您可以将过滤条件放在subquery
或主query
中。只关注在A中过滤0
(无)C的情况。