Ibolit
Ibolit

Reputation: 9720

Django: select status, count(status) from table group_by status;

I know that there is no group_by in Django for some reason. However, I need to get the number of items in each of the possible statuses. It can be done with a very simple query:

select status, count(status) from table group_by status;

At the same time, in our project we try to do as much as possible in Django ORM, and so far have never used raw SQL anywhere except in some migrations.

Is there a way to do this in Django ORM without getting duplicates?

Upvotes: 0

Views: 164

Answers (2)

dirkgroten
dirkgroten

Reputation: 20692

You can use values() to group your queryset.

from django.db.models import Count
MyModel.objects.values('status').annotate(num=Count('status'))

will return <QuerySet [{'status': 1, 'num': 4}, {'status': 2, 'num': 12}...]>

Note: if you have any ordering on your model or on your default manager, you'll have to remove that first by adding order_by().

Upvotes: 1

ruddra
ruddra

Reputation: 51988

You can try like this(with annotation):

from django.db.models import Count    
YourModel.objects.values('status').annotate(status_count=Count('status'))

Upvotes: 1

Related Questions