Count and group by equivalent in Django Queryset

While working on a Django project, I came through a problem. I wanted to select  a column & count of that column group by that column from a table. (categoryname & count  of items for each category), so in simple SQL it would be as simple as this:

SELECT column_name , COUNT(column_name) FROM TableName GROUP BY column_name;

Now Django Sub Query for the following given SQL code would be.

data = MyModel.objects.filter(column_1_gt = 'some value').values('column_name').order_by().annotate(Count('column_name'))

  • values(‘column_name) –  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.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s