sqlalchemy - Count of related records in many-to-many relationship -
I am trying to create a classmap that gives the number of members connected to a project, I tried: / P>
class of # method project # classmathape def member_count (CLS, project_id): return session. (Project message). Filter (project message. Project. _ == project_id). Count ()
Many-to-many relationships are defined as:
class members (base): __tablename__ = 'member' id Project_list = relationship ("project message", backref = "member") class project (base) = column (integer, primary_key) = true ()) = entry = column (string (50), exclusive = true, empty = incorrect) : __tablename__ = 'project' id = Column, primary_keys = true (name) = column (string (100), exclusive = true, empty = fail) class projectmember (base): __tablename__ = 'project_member' project_id = column (integer, foreign ("Project.id"), tapable = project = relation ("project", backf = "project_mail") is_pm = column (boolean, falls, primary_kize = true) member_id = column (integer, forex ("member.id
Use a simple asset like the one below, which is the children's count page Will use the current session
class project (...): # ... @property def member_digit (full): return object_ession (self). Some (projectmember) .with_parent ( AutoCount () print (my_proj.member_count_simple) # @ note: will issue a SQL statement
or use:
class project (base ): # ... @ hybrid_property DR member member number (self): return object_ession (self). Some (projectmember) .with_parent (self Yum) .count () @ member_count.expressiondef_member_count_expression (CLS): Select q = ([func.count (ProjectMember.project_id)]) \ where (ProjectMember.project_id == cls.id) \ label (". . Member control ") return q
... in this situation you can get your query (for example, filter
and order_by
) You can use this expression in:
qry = (session.query (Project, Project.member_count) .order_by (Project.member_count.desc ())) # @note: For this Tuples (project, MEMBER_COUNT) returns (proj, cnt_mem) in qry .all (): print (proj.name, cnt_mem)
Comments
Post a Comment