我正在尝试创建一个classmethod,它返回与项目关联的成员数。我试过了:
# 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')
谢谢!
答案 0 :(得分:4)
使用下面的简单属性,它将使用实例的当前会话来获取子项数
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
和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)