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
                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())
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With