django 分组统计遇见的问题

在使用 django 的时候发现了一个

例如:

In [54]: print(F.objects.all().values("age").annotate(fff=Count("age")).query)
SELECT "a_f"."age", COUNT("a_f"."age") AS "fff" FROM "a_f" GROUP BY "a_f"."age"

看上去也毫无问题,可是我换一个表

In [56]: print(F.objects.all().values("attack_type").annotate(total=Count("attack_type")).query)
SELECT "b_f"."type", COUNT("b_f"."type") AS "total" FROM "b_f" GROUP BY "b_f"."id" ORDER BY "b_f"."id" DESC

神奇的事情发生了.他竟然变成了 ORDER BY "b_f"."id" ,而且还加上了ORDER BY "b_f"."id" DESC,而且还会报错:

报错信息如下:
ProgrammingError: column "b_f.type" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: SELECT "b_f"."type", COUNT("...

通过查询,找到一个答案,Django ORM Group By ID

发现加上order_by()就可以避免这个问题.

In [58]: print( RequestLogBasic.objects.all().values("type").annotate(total=Count("type")).order_by("type").query)
SELECT "b_f"."type", COUNT("b_f"."type") AS "total" FROM "b_f" GROUP BY "b_f"."type" ORDER BY "b_f"."type" ASC
原文地址:https://www.cnblogs.com/twotigers/p/9809219.html