Annotations and expressions

annotate() adds to each object of a QuerySet a value computed by the database, such as a count or a sum, using ORM expressions (Count, Sum, F, Q, Case). The calculation is done in SQL, which avoids looping in Python. The annotated values can then be used to filter or sort.

Example

Author.objects.annotate(nb_posts=Count('posts')).order_by('-nb_posts')

Related concepts

The whole glossary