Django equivalent of COUNT with GROUP BY

Imran picture Imran · May 9, 2009 · Viewed 22.2k times · Source

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?

Answer

Alex Koshelev picture Alex Koshelev · May 9, 2009

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.