Django查询注释和汇总

时间:2018-10-09 10:54:53

标签: django

如何在Django中编写这样的查询?

  select sum(kolvo), reason
  from(
  select count(reason) kolvo, reason
  from contacts group by reason) group by reason

1 个答案:

答案 0 :(得分:0)

您的查询在语义上等效于:

SELECT count(reason) AS kolvo,
       reason
FROM contacts
GROUP BY reason

因此无需外部查询。

您可以使用以下命令在Django的ORM中进行此类查询:

Contacts.objects.values('reason').annotate(
    kolvo=Count('id')
).order_by('reason')

然后,这将返回一个包装字典的QuerySet,例如:

< QuerySet [
    { 'reason': 'some reason', 'kolvo': 13 },
    { 'reason': 'some other reason', 'kolvo': 2 },
] >