简体   繁体   English

SQLAlchemy查询具有关系计数的对象

[英]SQLAlchemy query for object with count of relationship

Lets say I have SQL Alchemy ORM classes: 可以说我有SQL Alchemy ORM类:

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. 但是,这显然是1 + n查询,这很糟糕。 What is the correct way to do this, with 1 query? 使用1个查询执行此操作的正确方法是什么? In normal SQL, I would do this with something along the lines of: 在普通的SQL中,我会使用以下内容执行此操作:

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

Construct a subquery that groups and counts session ids from runs, and join to that in your final query. 构造一个子查询,该子查询对运行中的会话ID进行分组和计数,并加入到最终查询中的会话ID。

sq = session.query(Run.session_id, func.count(Run.session_id).label('count')).group_by(Run.session_id).subquery()
result = session.query(Session, sq.c.count).join(sq, sq.c.session_id == Session.id).all()

The targeted SQL could be produced simply with: 目标SQL可以简单地生成:

db.session.query(Session, func.count(Run.id)).\
    outerjoin(Run).\
    group_by(Session.id).\
    order_by(Session.id.desc())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM