Filtering only on Annotations in Django

Viewed 21251
6 Answers

You can use the annotation variable in the filter.

publishers=Publisher.objects.annotate(num_books=Count('book')).filter(num_books__gte=2)

Starting Django 2.0 one may use filter parameter of aggregation function:

from django.db.models import Q    
Publisher.objects.annotate(num_books=Count('book', filter=Q(book__rating__gt=3.0)))

The answer is based on a cheat sheet.

Related