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:
Given that
teamsis basically a list, and therefore has nototal_goalsas that belongs to eachteaminstance, is there a way to sum the value ofteamgoals without the for loop?If 1 is possible, is it faster/better than the for loop above?