与GROUP BY相当于COUNT的Django [英] Django equivalent of COUNT with GROUP BY
本文介绍了与GROUP BY相当于COUNT的Django的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
SELECT player_type,COUNT(*)FROM players GROUP BY player_type;
是否可以使用Django 1.1的Model Query API,还是应该使用简单的SQL? p>
解决方案
如果您使用的是Django 1.1 beta(trunk):
Player.objects.values('player_type')。order_by()。annotate(Count('player_type'))
-
values('player_type')
- 仅包含player_type
field into
GROUP BY
子句 -
order_by()
- 排除可能导致不需要的字段包含在SELECT
和GROUP BY
中的默认排序。
I know Django 1.1 has some new aggregation methods. However I couldn't figure out equivalent of the following query:
SELECT player_type, COUNT(*) FROM players GROUP BY player_type;
Is it possible with Django 1.1's Model Query API or should I just use plain SQL?
解决方案
If you are using Django 1.1 beta (trunk):
Player.objects.values('player_type').order_by().annotate(Count('player_type'))
values('player_type')
- for inclusion onlyplayer_type
field intoGROUP BY
clause.order_by()
- for exclusion possible default ordering that can cause not needed fields inclusion inSELECT
andGROUP BY
.
这篇关于与GROUP BY相当于COUNT的Django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文