#How This Annotation Works?

7 messages · Page 1 of 1 (latest)

rapid sphinx
#

Reading the Aggregation Topic Guide I came across this:

Given:

  • Publisher A has two books with ratings 4 and 5.

  • Publisher B has two books with ratings 1 and 4.

  • Publisher C has one book with rating 1.

>>> a, b = Publisher.objects.filter(book__rating__gt=3.0).annotate(num_books=Count("book"))
>>> a, a.num_books
(<Publisher: A>, 2)
>>> b, b.num_books
(<Publisher: B>, 1)

It's stated that, this query:

counts the number of books that have a rating exceeding 3.0 for each publisher. The filter precedes the annotation, so the filter constrains the objects considered when calculating the annotation.

If the constrained objects in this query are Publisher objects and not Book objects, how the annotation knows that it should count only the num_books where book__rating__gt=3? Why num_books in Publisher b is equal to 1 instead of 2? I understand it logically, but don't understand how Django understands that. What am I missing?

vernal flume
#

because, as you pasted

the filter constrains the objects considered when calculating the annotation

#

constrains, i.e. limits, filters.

#

If you want it more spesifically, look at

>>> queryset = Publisher.objects.filter(book__rating__gt=3.0).annotate(num_books=Count("book"))
>>> print(queryset.query)
rapid sphinx
vernal flume
#

Print the query and look at it 🙂

#

or maybe even share it here, and i can probably explain if you are still lost.