Django orm group_by

时间:2015-08-05 15:33:53

标签: django django-models orm group-by django-orm

有没有办法通过特定列告诉Django ORM GROUP BY ?这样的事情。

SELECT pk, somecol1, somecol2 somecol3 MIN(somecol2) AS first, COUNT(somecol2) AS count FROM customer GROUP BY somecol2

根据Django ORM文档,可以 GROUP BY

一些例子:

SomeModel.objects.annotate(Count('somecol')) GROUP BY:模型的所有字段

SomeModel.objects.values('name').annotate(Count('somecol'))

GROUP BY:名称

SomeModel.objects.annotate(Count('somecol')).values('name') GROUP BY:模型的所有cols

SomeModel.objects.values('name', 'pk').annotate(Count('somecol')).values('pk') GROUP BY:name,pk

SomeModel.objects.values('name').annotate(Count('somecol')).values('pk') GROUP BY:name,pk

为什么不能选择GROUP BY子句,如下例所示。

SomeModel.objects.values('pk', 'somecol1', 'somecol2', 'somecol3').annotate(Count('somecol2'))

OR

SomeModel.objects.values('pk', 'somecol1', 'somecol2', 'somecol3').annotate(Count('somecol2')).group_by('somecol2')

GROUP BY:is_active

1 个答案:

答案 0 :(得分:0)

简短的回答是肯定的。这是聚合的文档,有一个方便的备忘单:

https://docs.djangoproject.com/en/1.8/topics/db/aggregation/

祝你好运。