I'm having difficulties constructing a query whereby A
objects are filtered by C
count, where C
is a grandchild of A
. This is my current (simplified) models code:
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')
I've tried the following queries, without success:
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"
All help greatly appreciated.
With the help of 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
)
You can put the filter condition in either the subquery
or the main query
. Only be careful with the case of filtering for 0
(none) Cs in A.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.