Using QuerySet annotate()
A snippet showing how to use annotate() for query calculations.
# models.py
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books')
pages = models.IntegerField(default=0)
def __str__(self):
return self.title
# views.py
from django.shortcuts import render
from django.db.models import Sum
from .models import Author
def author_list(request):
qs = Author.objects.annotate(total_pages=Sum('books__pages'))
return render(request, 'authors.html', {'authors': qs})
Explanation:
-
annotate()adds calculated fields (aggregates) to each object in a QuerySet. -
Common aggregations include
Sum,Count,Avg,Max, andMin. - In this example, we calculate the total number of pages for each author by summing their book pages.
- Useful for statistics like total sales per customer, number of posts per user, or total items in an order.
- Category Models & ORM
- Total Views 804
- Last Modified 26 October, 2025
- Tags #queryset #annotate #orm #aggregation
Previous snippet
Using QuerySet values()
Next snippet