SQLAlchemy: Sum all Child column attributes while querying Parent?

十年热恋 提交于 2019-12-08 09:35:35

问题


I have a many-to-one relationship between Team and League

The following code joins the tables, and orders the leagues by goals_for for each team in that 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)

Correctly produces:

Total goals scored in Germany Bundesliga is 22

Total goals scored in English Premier League is 15

I'm wondering about two things:

  1. Given that teams is basically a list, and therefore has no total_goals as that belongs to each team instance, is there a way to sum the value of team goals without the for loop?

  2. If 1 is possible, is it faster/better than the for loop above?


回答1:


Why not try to get aggregate result directly from the SQL query, and avoid retrieving extra data from the database and loading whole relationship tree.

Following should given you an idea:

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)


来源:https://stackoverflow.com/questions/41152973/sqlalchemy-sum-all-child-column-attributes-while-querying-parent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!