Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy query for object with count of relationship

Lets say I have SQL Alchemy ORM classes:

class Session(db.Model):
  id = db.Column(db.Integer, primary_key=True)
  user_agent = db.Column(db.Text, nullable=False)

class Run(db.Model):
  id = db.Column(db.Integer, primary_key=True)

  session_id = db.Column(db.Integer, db.ForeignKey('session.id'))
  session = db.relationship('Session', backref=db.backref('runs', lazy='dynamic'))

And I want to query for essentially the following:

((session.id, session.user_agent, session.runs.count())
  for session in Session.query.order_by(Session.id.desc()))

However, this is clearly 1+n queries, which is terrible. What is the correct way to do this, with 1 query? In normal SQL, I would do this with something along the lines of:

SELECT session.id, session.user_agent, COUNT(row.id) FROM session
LEFT JOIN rows on session.id = rows.session_id
GROUP BY session.id ORDER BY session.id DESC
like image 853
WirthLuce Avatar asked Oct 20 '13 23:10

WirthLuce


1 Answers

The targeted SQL could be produced simply with:

db.session.query(Session, func.count(Run.id)).\
    outerjoin(Run).\
    group_by(Session.id).\
    order_by(Session.id.desc())
like image 192
Ilja Everilä Avatar answered Oct 10 '22 11:10

Ilja Everilä