多对多关系中的相关记录计数
Posted
技术标签:
【中文标题】多对多关系中的相关记录计数【英文标题】:Count of related records in many-to-many relationship 【发布时间】:2014-09-24 17:22:14 【问题描述】:我正在尝试构建一个类方法,它返回与项目关联的成员数。我试过了:
# 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')
谢谢!
【问题讨论】:
当您尝试执行该方法时会发生什么?你有错误吗? 【参考方案1】:使用如下所示的简单属性,它将使用实例的当前会话来获取孩子的数量
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
...在这种情况下,您可以在查询中使用此表达式(例如filter
s 和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)
【讨论】:
货车,object_session(self).
来自哪里?
docs.sqlalchemy.org/en/rel_0_9/orm/…以上是关于多对多关系中的相关记录计数的主要内容,如果未能解决你的问题,请参考以下文章