我有以下代码段:
sum_games = GameHistory.objects.all().aggregate(Sum('games'))
sum_played = GameHistory.objects.all().aggregate(Sum('games_played'))
sum_goals = GameHistory.objects.all().aggregate(Sum('goals'))
sum_assists = GameHistory.objects.all().aggregate(Sum('assists'))
sum_clean_sheet = GameHistory.objects.all().aggregate(Sum('clean_sheet'))
什么是最好,最简洁的写方法?因为现在我只是在重复自己,但变量不同。
谢谢。
答案 0 :(得分:3)
您可以用逗号分隔它们。
stats = GameHistory.objects.all().aggregate(sum_games=Sum('games'), sum_games_played=Sum('games_played'), ...)
然后像这样访问:
print(stats['sum_games'])
print(stats['sum_games_played'])
https://docs.djangoproject.com/en/2.2/topics/db/aggregation/#joins-and-aggregates