我之间有许多对一的关系Team和League
Team
League
下面的代码加入表,订单联赛由goals_for每个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
德国德甲联赛的总进球数是22
英超联赛的总进球数是15
我想知道两件事:
鉴于这teams基本上是一个列表,因此没有total_goals属于每个team实例的列表,有没有办法在team没有for循环的情况下求和目标值?
teams
total_goals
如果可能为1,是否比上面的for循环更快/更好?
为什么不尝试直接从SQL查询中获取聚合结果,并避免从数据库中检索额外的数据并加载整个关系树。
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)