How to perform GROUP BY Query using django

0 votes
59 views
asked Aug 3, 2017 by anonymous

I have a simple employer model with basic info and group (group id as a foreign key).

class Employer(Model):
    first_name = ..
    last_name = ..
    designation = model.ForeignKey(Designation)

using MySql i can use group_by query like this

SELECT group, COUNT(group) AS gcount
FROM employer GROUP BY group

How can i achieve it via django ORM or can say how to group by using django ??

Looking for something like Employer.objects.group_by('group').count('group')

2 Answers

0 votes
answered Aug 3, 2017 by anonymous

There is also an external solution via

pip install django-group-by

You can do

some_rows = Book.objects.group_by('title', 'author', 'author__nationality').distinct()
some_rows.count()
0 votes
answered Aug 3, 2017 by anonymous

Your SQL

SELECT group, COUNT(group) AS gcount
FROM employer GROUP BY group

Equivilent via django ORM can be achieved using.

from django.db.models import Count
Employer.objects.values('group').annotate(gcount=Count('group'))
...