Using QuerySet aggregate()

A snippet showing how to use aggregate() for sums, counts, and averages.


# models.py

from django.db import models

class Order(models.Model):
    customer = models.CharField(max_length=100)
    total_amount = models.DecimalField(max_digits=10, decimal_places=2)

    def __str__(self):
        return f"Order by {self.customer}"
  

# views.py

from django.shortcuts import render
from django.db.models import Sum, Avg, Max, Min
from .models import Order

def order_aggregates(request):
    totals = Order.objects.aggregate(
        total_sum=Sum('total_amount'),
        total_avg=Avg('total_amount'),
        total_max=Max('total_amount'),
        total_min=Min('total_amount'),
    )
    return render(request, 'orders/aggregates.html', {'totals': totals})
  
Explanation:
  • aggregate() computes summary values across the entire QuerySet, returning a dictionary.
  • You can use multiple aggregation functions at once, like Sum, Avg, Max, and Min.
  • Unlike annotate(), which adds fields per row, aggregate() collapses everything into one summary result.
  • Useful for reporting totals, averages, or min/max values across your entire dataset.
  • Category Models & ORM
  • Total Views 512
  • Last Modified 31 October, 2025
  • Tags #queryset #aggregate #orm #aggregation
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.