使用django ORM进行多级注释/聚合

时间:2018-02-28 07:58:49

标签: django django-models django-orm django-aggregation

我一直在努力实现与query-for-total-score

中完全相同的功能

Django是否支持多级聚合?我可以获得每个用户每次挑战的最高分数,但我不知道如何深入挖掘我的结果以适应。

s = Submission.objects.values('challenge','user').annotate(Max('score'),Max('total_score'))

这给了我带有用户,挑战,总分和分数

的dict列表

我想要的是每个用户的得分总和。当我在这上面使用聚合时,我得到所有得分的总和

s.aggregate(Sum('total_score__max'),Sum(score__max))

Postgres sql查询看起来像这样

select "user_id", SUM("score__max") as "score", SUM("total_score__max") as "total_score", COUNT("challenge_id") as "count" from 
(SELECT "submission"."user_id", "submission"."challenge_id", MAX("submission"."score")
AS "score__max", MAX("submission"."total_score") AS "total_score__max" FROM "submission" 
GROUP BY "submission"."user_id", "submission"."challenge_id")t GROUP BY "user_id" ORDER BY "user_id";

0 个答案:

没有答案