我在Team
和League
以下代码加入表格,并为goals_for
中的每个team
按league
为联盟排序:
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
我想知道两件事:
鉴于teams
基本上是一个列表,因此没有属于每个total_goals
实例的team
,有没有办法对{{{{}}的值求和1}}没有for循环的目标?
如果可能为1,它是否比上面的for循环更快/更好?
答案 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)