Pegase745 / sqlalchemy-datatables

SQLAlchemy integration of jQuery DataTables >= 1.10.x (Pyramid and Flask examples)
MIT License
159 stars 67 forks source link

How can I use "count" for another relevant table? #64

Closed ghostbody closed 7 years ago

ghostbody commented 7 years ago

I have the following schema for my ORM:

Table Member

class CourseMember(Base):
    __tablename__ = 'member'

    member_id = Column(BigInteger, primary_key=True)
    team_id = Column(ForeignKey(team.team_id', ondelete=u'CASCADE', onupdate=u'CASCADE'), nullable=False)
    # more attributes....
    team = relationship('Team')

Table Team

class Team(Base):
    __tablename__ = 'team'

    team_id = Column(BigInteger, primary_key=True)
    name = Column(String(64), nullable=False)
    # more attributes

I am wondering how to build a dataTable using datatable-sqlachemy to get the flowing items:

(team_id, team_name, team_member_count)

I do not know how to count the members with only one class int session.query(Team).cascaded_operations()

Is there a possible way for this usage? Thank you very much.

tdamsma commented 7 years ago

Could you please try and see if the recent updates would solve your issue? It should look something like this:


from sqlalchemy import func

columns = [
    ColumnDT(Team.team_id),
    ColumnDT(Team.name),
    ColumnDT(func.count(CourseMember. member_id)
]

query=session.query().\
    select_from(Team).\
    join(CourseMember).\
    group_by(Team.team_id, Team.name)