mirror of
https://github.com/django/django.git
synced 2025-06-05 03:29:12 +00:00
Added documentation about different results according to order of annotate() and filter() in a query.
This commit is contained in:
parent
9da2210f12
commit
e108cb4a57
@ -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
|
query asks for the average of a publisher's book's ratings for only those
|
||||||
ratings exceeding 3.0.
|
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
|
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
|
queries so when in doubt, inspect the SQL with ``str(queryset.query)`` and
|
||||||
write plenty of tests.
|
write plenty of tests.
|
||||||
|
Loading…
x
Reference in New Issue
Block a user