Django, aggregate and annotate method
Introduction
In Django, aggregate and annotate are two very useful methods, they used to perform operations on querysets, but they serve different purposes
aggregate method
This method is used to perform aggregate functions (e.g., Count, Sum, Avg, Min, Max) on a queryset. It return a dictionary, that contains the result of aggregate functions, collapses the entire queryset into a single value based on the aggregation functions applied. it doesn't return new queryset's, it means you can't reuse this with (like can't apply filter method etc).
To use aggregation on a queryset, we basically use aggregate() method.
Example
Here in this example, i want to calculate the average price of all books.
from django.db.models import Avg
from .models import Book
book = Book.objects.all().aggregate (Avg("price"))
here django will automatically generate the key pricc__avg on the base of (field_namc__aggregato function), hence if you want to change the key, you can
mention the key also
from django.db.models import Avg
from .models import Book
book = Book.objects.all().aggregate(avg_price=Avg("price"))
annotate method
This method is used to add annotations to each object in the queryset. An annotation is an additional field added to each object in the queryset based on some computation or aggregation. Unlike aggregate(), annotate() does not collapse the queryset into a single value but rather adds new fields to each object in the queryset. It return a new queryset's, it means can reuse with filter method for chaining.
To use annotation on a queryset, we basically use annotate method.
Example
annotate method will add an additional field called entry__count in each object in the queryset’s
from django.db.models import Count
from .models import Book
book = Blog.objects.annotate(Count("entry"))
you can even access each field of each object
>>> q[0].name
>>> 'python'
this will return the number of entries on the first blog
>>> q[0].entry_count
>>> 42