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

How to Perform GROUP BY Queries in Django?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-11 02:22:09593browse

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()
)

This code translates to a SQL query similar to:

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

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}]

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

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

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!

Statement:
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