在SQLAlchemy中由孙子过滤

时间:2014-09-18 13:46:56

标签: python sqlalchemy

我在构建查询时遇到困难,A个对象按C计数进行过滤,其中CA的孙子。这是我目前的(简化)模型代码:

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"

所有人都非常感谢。

1 个答案:

答案 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的情况。