Count of related records in many-to-many relationship

半腔热情 提交于 2019-11-29 17:13:37

Either use a simple property like below, which will use the current session of the instance to get count of children

class Project(...):
    # ...
    @property
    def member_count_simple(self):
       return object_session(self).query(ProjectMember).with_parent(self).count()


print(my_proj.member_count_simple) # @note: will issue an SQL statement

or use Hybrid Attribute:

class Project(Base):
    # ...

    @hybrid_property
    def member_count(self):
        return object_session(self).query(ProjectMember).with_parent(self).count()

    @member_count.expression
    def _member_count_expression(cls):
        q = select([func.count(ProjectMember.project_id)]).\
                where(ProjectMember.project_id == cls.id).\
                label("member_count")
        return q

... in which case you can use this expression in your query (filters and order_by, for example):

qry = (session.query(Project, Project.member_count)
        .order_by(Project.member_count.desc())
        )
# @note: it returns tuples (Project, member_count)
for (proj, cnt_mem) in qry.all():
    print(proj.name, cnt_mem)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!