Home > Backend Development > Python Tutorial > How to Perform GROUP BY Queries in Django?

How to Perform GROUP BY Queries in Django?

Patricia Arquette
Release: 2024-12-11 02:22:09
Original
634 people have browsed it

How to Perform GROUP BY Queries in Django?

How to Achieve Group By Query in Django?

In Django, to perform a group by query on a model, one can employ the aggregation features of the ORM. This is achieved by utilizing the values() and annotate() methods.

Consider the following example:

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

This code translates to a SQL query similar to:

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

The result of the query will be a list of dictionary objects, each representing a group. For instance:

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

To include multiple fields in the results, simply add them as arguments to values():

    .values('designation', 'first_name', 'last_name')
Copy after login

References:

  • Django documentation: values(), annotate(), and Count
  • Django documentation: Aggregation, especially the section on Interaction with default ordering or order_by()

The above is the detailed content of How to Perform GROUP BY Queries in Django?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template