小编典典

SQLAlchemy:在查询父级时汇总所有子级列属性?

sql

我之间有许多对一的关系TeamLeague

下面的代码加入表,订单联赛由goals_for每个teamleague

for league in League.query.join(League.teams).order_by(desc(Team.goals_for)):
    total_goals = 0
    for team in league.teams:
        total_goals += team.goals_for

    print("Total goals scored in", league.full_name, "is", total_goals)

正确产生:

德国德甲联赛的总进球数是22

英超联赛的总进球数是15

我想知道两件事:

  1. 鉴于这teams基本上是一个列表,因此没有total_goals属于每个team实例的列表,有没有办法在team没有for循环的情况下求和目标值?

  2. 如果可能为1,是否比上面的for循环更快/更好?


阅读 178

收藏
2021-05-16

共1个答案

小编典典

为什么不尝试直接从SQL查询中获取聚合结果,并避免从数据库中检索额外的数据并加载整个关系树。

以下应该给你一个想法:

from sqlalchemy import func

q = (
    session
    .query(League.full_name, func.sum(Team.goals_for).label("total_goals"))
    .join(Team, League.teams)
    .group_by(League.full_name)
)

for full_name, total_goals in q:
    print("Total goals scored in", full_name, "is", total_goals)
2021-05-16