Annotation

Annotation: Annotation is used to add extra information to each record in a queryset. You can add calculated fields to the records in the queryset without changing the underlying data in the database.

Let's say we want to annotate each Order object with the number of items in that order:

from django.db.models import F
from myapp.models import Order, OrderItem

# Annotate each order with the count of items
orders_with_item_count = Order.objects.annotate(item_count=Count('orderitem'))

for order in orders_with_item_count:
    print(f"Order #{order.id} has {order.item_count} items.")

In this example, we're using the annotate method to add an item_count field to each Order object. This field is calculated based on the related OrderItem records associated with each order.

Last updated