How to Use Aggregate in Django: Syntax and Examples
In Django, use the
aggregate() method on a queryset to perform calculations like sum, average, count, min, and max. You pass aggregation functions such as Sum() or Count() inside aggregate() to get the result as a dictionary.Syntax
The aggregate() method is called on a Django queryset and takes one or more aggregation functions as keyword arguments. Each argument names the result key and uses an aggregation function like Sum(), Count(), Avg(), Min(), or Max() applied to a model field.
- queryset.aggregate(result_name=AggregationFunction('field_name'))
result_name: the key for the returned dictionaryAggregationFunction: one of Django's aggregation functions'field_name': the model field to aggregate
python
from django.db.models import Sum, Count, Avg, Min, Max # Example syntax result = MyModel.objects.aggregate( total=Sum('field_name'), count=Count('field_name'), average=Avg('field_name'), minimum=Min('field_name'), maximum=Max('field_name') )
Example
This example shows how to calculate the total price and average price of all products in a Product model using aggregate(). The result is a dictionary with keys total_price and average_price.
python
from django.db import models from django.db.models import Sum, Avg class Product(models.Model): name = models.CharField(max_length=100) price = models.DecimalField(max_digits=8, decimal_places=2) # Calculate total and average price result = Product.objects.aggregate( total_price=Sum('price'), average_price=Avg('price') ) print(result)
Output
{'total_price': Decimal('12345.67'), 'average_price': Decimal('123.46')}
Common Pitfalls
Common mistakes when using aggregate() include:
- Calling
aggregate()without parentheses on the queryset (it must be called as a method). - Using aggregation functions without importing them from
django.db.models. - Expecting
aggregate()to return a queryset instead of a dictionary. - Trying to chain
aggregate()with other queryset filters after calling it (it returns a dictionary, so chaining fails).
python
from django.db.models import Sum # Wrong: forgetting parentheses # result = Product.objects.aggregate # Wrong: no import of Sum # result = Product.objects.aggregate(total=Sum('price')) # Correct usage result = Product.objects.aggregate(total=Sum('price')) print(result)
Output
{'total': Decimal('12345.67')}
Quick Reference
| Aggregation Function | Description | Example Usage |
|---|---|---|
| Sum | Calculates the sum of a field | aggregate(total=Sum('field_name')) |
| Count | Counts the number of non-null values | aggregate(count=Count('field_name')) |
| Avg | Calculates the average value | aggregate(avg=Avg('field_name')) |
| Min | Finds the minimum value | aggregate(min=Min('field_name')) |
| Max | Finds the maximum value | aggregate(max=Max('field_name')) |
Key Takeaways
Use
aggregate() on a queryset with aggregation functions to get summary data as a dictionary.Always import aggregation functions like
Sum and Count from django.db.models.aggregate() returns a dictionary, not a queryset, so you cannot chain it further.Aggregation functions work on model fields and return results keyed by the names you provide.
Common functions include
Sum, Count, Avg, Min, and Max.