VOOZH about

URL: https://www.geeksforgeeks.org/python/aggregate-vs-annotate-in-django/

⇱ Aggregation and Annotation in Django - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Aggregation and Annotation in Django

Last Updated : 11 May, 2026

Django's ORM offers tools for querying and performing calculations on database data. Two commonly used methods are aggregate() and annotate().

  • aggregate() summarizes data across the entire queryset (e.g., total, average, count).
  • annotate() computes and adds calculated values for each individual object in the queryset.

aggregate() vs annotate()

aggregate()annotate()
Performs calculations over the entire queryset.Performs calculations for each object in the queryset.
Returns a dictionary with computed values.Returns a queryset with extra computed fields added to each object.
Example: Book.objects.aggregate(total_price=Sum('price')) returns {'total_price': 5000}Example: Author.objects.annotate(num_books=Count('book')) adds a num_books field to each author
Use for summary statistics like total, average, max, min.Use for per-object analytics like counts, sums, or averages for each object.
Scope is global for the queryset.Scope is individual per object.

Example

Consider a project named 'bookstore_project' having an app named 'store'. The app contains two models, Author and Book and we will perform aggregations to analyze book data.

Sample Dataset

Using aggregate()

Calculate the total number of books and the average price of all books in the bookstore.

Output

{'total_books': 4, 'average_price': 18.81, 'total_price': 76.24}

In this example, aggregate() summarizes the dataset by calculating the total number of books, the average price and the combined price of all books.

Using annotate()

Calculate the number of books and the average price of books for each author.

Output

# John Doe - Total Books: 2, Average Price: 22.74
# Jane Smith - Total Books: 2, Average Price: 15.38

annotate() adds total_books and average_price fields to each Author record, showing the count of books and the average price per author.

Comment
Article Tags:
Article Tags: