我想获取MyModel order_by(' - end_date')的最后100条记录,并对不同的获胜者类型进行SUM注释
MyModel.objects.all()[:100].order_by('-end_game_time').values('winner').annotate(total=Count('winner'))
结果查询如下,我没有预期的组
<QuerySet [{'winner': 3, 'total': 1}, {'winner': 15, 'total': 1}, 'total': 1}, {'winner': 3, 'total': 1}, {'winner': 5, 'total': 1}, {'winner': 15, 'total': 1}, {'winner': 5, 'total': 1}, {'winner': 3, 'total': 1}, '...(remaining elements truncated)...']>
生成的查询就像
SELECT "game_mymodel"."winner", COUNT("game_mymodel"."winner") AS "total" FROM "game_mymodel" GROUP BY "game_mymodel"."winner", "game_mymodel"."end_game_time" ORDER BY "game_mymodel"."end_game_time" DESC LIMIT 100
但是当我没有order_by时,结果就像我预期的那样
MyModel.objects.all()[:100].values('winner').annotate(total=Count('winner'))
Out[52]: <QuerySet [{'winner': 5, 'total': 43}, {'winner': 1, 'total': 2}, {'winner': 15, 'total': 51}, {'winner': 2, 'total': 42}, {'winner': 3, 'total': 43}]>
和生成的查询group_by部分不同
SELECT "game_mymodel"."winner", COUNT("game_mymodel"."winner") AS "total" FROM "game_mymodel" GROUP BY "game_mymodel"."winner" LIMIT 100
答案 0 :(得分:3)
据我所知,在单个查询中无法实现您想要的功能,您在SQL中想要的是:
SELECT "game_mymodel"."winner", COUNT("game_mymodel"."winner") AS "total" FROM "game_mymodel" GROUP BY "game_mymodel"."winner" ORDER BY "game_mymodel"."end_game_time" DESC LIMIT 100
这不是一个有效的SQL查询,因此您需要有一个子查询来选择100个元素,然后对它们应用聚合。
首先构建子查询:
top_100_games = MyModel.objects.order_by('-end_game_time')[:100].only('id').all()
然后在主查询中使用它:
MyModel.objects.filter(id__in=top_100_games).values('winner').annotate(total=Count('winner'))