简体   繁体   English

按SQLAlchemy中的孙子计数过滤

[英]Filter by grandchildren count in SQLAlchemy

I'm having difficulties constructing a query whereby A objects are filtered by C count, where C is a grandchild of A . 我在构造查询时遇到困难,其中A对象按C计数进行过滤,其中CA的孙子。 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 : 借助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 . 您可以将过滤条件放在subquery或主query Only be careful with the case of filtering for 0 (none) Cs in A. 仅注意在A中过滤0 (无)Cs的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM