twotigers

在使用 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

分类:

技术点:

相关文章:

  • 2021-12-18
  • 2021-10-03
  • 2021-11-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-03
  • 2021-09-17
  • 2021-10-14
猜你喜欢
  • 2021-10-19
  • 2021-09-11
  • 2022-02-09
  • 2022-12-23
  • 2021-12-22
  • 2022-01-15
  • 2021-07-17
相关资源
相似解决方案