SQLAlchemy:在查询Parent时求和所有子列属性?

时间:2016-12-14 22:00:08

标签: python sql sqlalchemy flask-sqlalchemy

我在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,有没有办法对{{{{}}的值求和1}}没有for循环的目标?

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

1 个答案:

答案 0 :(得分: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)