多个关系中相关记录的计数

2024-10-01 09:32:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图构建一个classmethod,它返回与项目相关联的成员数。我试过了:

# method of class Project
@classmethod
def member_count(cls, project_id):
   return Session.query(ProjectMember).\
            filter(ProjectMember.project_id==project_id).count()

多对多关系定义为:

^{pr2}$

谢谢!


Tags: of项目projectidreturndefcountmethod
1条回答
网友
1楼 · 发布于 2024-10-01 09:32:45

或者使用下面这样的简单属性,它将使用实例的当前会话来获取子级的计数

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

或使用^{}

^{pr2}$

。。。在这种情况下,可以在查询中使用此表达式(例如,filters和order_by):

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)

相关问题 更多 >