以下代码显示了所有内容。
class Parent(base): __tablename__ = 'parents' # ... @hybrid_property def child_count(self): #return len(self.children) # @note: use when non-dynamic relationship return self.children.count()# @note: use when dynamic relationship @child_count.expression def child_count(cls): return (select([func.count(Child.child_id)]). where(Child.parent_id == cls.parent_id). label("child_count") ) @hybrid_method def child_count_ex(self, stime, etime): return len([_child for _child in self.children if stime <= _child.time <= etime ]) @child_count_ex.expression def child_count_ex(cls, stime, etime): return (select([func.count(Child.child_id)]). where(Child.parent_id == cls.parent_id). where(Child.time >= stime). where(Child.time <= etime). label("child_count") )# usage of expressions:stime, etime = datetime.datetime(2012, 1, 1), datetime.datetime(2012, 1, 31)qry = session.query(Parent)#qry = qry.filter(Parent.child_count > 2)qry = qry.filter(Parent.child_count_ex(stime, etime) > 0)


