diff --git a/docs/topics/db/aggregation.txt b/docs/topics/db/aggregation.txt index d871c548e2..2e84c3108a 100644 --- a/docs/topics/db/aggregation.txt +++ b/docs/topics/db/aggregation.txt @@ -425,6 +425,27 @@ publisher's that have at least one book with a rating exceeding 3.0. The second query asks for the average of a publisher's book's ratings for only those ratings exceeding 3.0. +Using multivalued filtering against a previously annotated aggregation might +still yield duplicate results. + +Given: + +* Publisher A has two books with each having 100 pages. + +Here's an example demonstrating this behavior:: + + >>> a = Publisher.objects.annotate(total_pages(Sum("books__pages")) + >>> a.total_pages + 200 + >>> b = Publisher.objects.annotate(Sum("books__pages")).filter(books__in=Books.objects.all()) + >>> b.total_pages + 400 + +This is behavior is caused because ``filter()`` calls won't reuse multivalued +JOINS generated by previous ``annotate()`` or ``filter`` calls. To prevent issues, +you should filter after annotations (not the other way around) or use +``Aggregate.filter``. + It's difficult to intuit how the ORM will translate complex querysets into SQL queries so when in doubt, inspect the SQL with ``str(queryset.query)`` and write plenty of tests.