gpt4 book ai didi

python - 多对多关系中相关记录的计数

转载 作者:太空宇宙 更新时间:2023-11-04 10:33:17 25 4
gpt4 key购买 nike

我正在尝试构建一个类方法,它返回与项目关联的成员数。我试过:

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

多对多关系定义为:

class Member(Base):
__tablename__ = 'member'
id = Column(Integer, primary_key=True)
login = Column(String(50), unique=True, nullable=False)
project_list = relationship("ProjectMember", backref="member")

class Project(Base):
__tablename__ = 'project'
id = Column(Integer, primary_key=True)
name = Column(String(100), unique=True, nullable=False)

class ProjectMember(Base):
__tablename__ = 'project_member'
project_id = Column(Integer, ForeignKey("project.id"), nullable=False, primary_key=True)
member_id = Column(Integer, ForeignKey("member.id"), nullable=False, primary_key=True)
project = relationship("Project", backref = "project_member")
is_pm = Column(Boolean, default = True, nullable = False)
UniqueConstraint('project_id', 'member_id')

谢谢!

最佳答案

要么使用像下面这样的简单属性,它将使用实例的当前 session 来获取 child 的数量

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

或使用 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

...在这种情况下,您可以在查询中使用此表达式(例如,filterorder_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)

关于python - 多对多关系中相关记录的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25081358/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com