Django equivalent of COUNT with GROUP BY

我怕爱的太早我们不能终老 提交于 2019-11-27 05:13:29

问题


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?


回答1:


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 only player_type field into GROUP BY clause.
  • order_by() - for exclusion possible default ordering that can cause not needed fields inclusion in SELECT and GROUP BY.



回答2:


Django 1.1 does support aggregation methods like count. You can find the full documentation here.

To answer your question, you can use something along the lines of:

from django.db.models import Count
q = Player.objects.annotate(Count('games'))
print q[0]
print q[0].games__count

This will need slight tweaking depending on your actual model.

Edit: The above snippet generates aggregations on a per-object basis. If you want aggregation on a particular field in the model, you can use the values method:

from django.db.models import Count
q = Player.objects.values('playertype').annotate(Count('games')).order_by()
print q[0]
print q[0].games__count

order_by() is needed because fields that are in the default ordering are automatically selected even if they are not explicitly passed to values(). This call to order_by() clears any ordering and makes the query behave as expected.

Also, if you want to count the field that is used for grouping (equivalent to COUNT(*)), you can use:

from django.db.models import Count
q = Player.objects.values('playertype').annotate(Count('playertype')).order_by()
print q[0]
print q[0].playertype__count


来源:https://stackoverflow.com/questions/842031/django-equivalent-of-count-with-group-by

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!