Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query as GROUP BY in django?

I query a model:

Members.objects.all() 

And it returns:

Eric, Salesman, X-Shop Freddie, Manager, X2-Shop Teddy, Salesman, X2-Shop Sean, Manager, X2-Shop 

What I want is to know the best Django way to fire a group_by query to my database, like:

Members.objects.all().group_by('designation') 

Which doesn't work, of course. I know we can do some tricks on django/db/models/query.py, but I am just curious to know how to do it without patching.

like image 895
simplyharsh Avatar asked Mar 10 '09 10:03

simplyharsh


People also ask

What is QuerySet in Django?

A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.

What is annotation in Django?

Appending the annotate() clause onto a QuerySet lets you add an attribute to each item in the QuerySet, like if you wanted to count the amount of articles in each category. However, sometimes you only want to count objects that match a certain condition, for example only counting articles that are published.


1 Answers

If you mean to do aggregation you can use the aggregation features of the ORM:

from django.db.models import Count result = (Members.objects     .values('designation')     .annotate(dcount=Count('designation'))     .order_by() ) 

This results in a query similar to

SELECT designation, COUNT(designation) AS dcount FROM members GROUP BY designation 

and the output would be of the form

[{'designation': 'Salesman', 'dcount': 2},   {'designation': 'Manager', 'dcount': 2}] 

If you don't include the order_by(), you may get incorrect results if the default sorting is not what you expect.

If you want to include multiple fields in the results, just add them as arguments to values, for example:

    .values('designation', 'first_name', 'last_name') 

References:

  • Django documentation: values(), annotate(), and Count
  • Django documentation: Aggregation, and in particular the section entitled Interaction with default ordering or order_by()
like image 148
Guðmundur H Avatar answered Sep 17 '22 23:09

Guðmundur H