#33403: Annotate results change when filtering *after* the annotate
-------------------------------------+-------------------------------------
Reporter: karyon | Owner: nobody
Type: Uncategorized | Status: closed
Component: Database layer | Version: 4.0
(models, ORM) |
Severity: Normal | Resolution: invalid
Keywords: | Triage Stage:
| Unreviewed
Has patch: 0 | Needs documentation: 0
Needs tests: 0 | Patch needs improvement: 0
Easy pickings: 0 | UI/UX: 0
-------------------------------------+-------------------------------------
Comment (by karyon):
Hi Simon, I'm sorry if I was unclear. I didn't intend this to be a
question, I already have a workaround in place. This was intended to be a
bug report: Two sections/sentences in the documentation are incorrect as
to which cases should or should not work, see the last paragraph of my
report.
In particular, I think the entire section "combining multiple
aggregations" should be generalized, since it's not only a second
annotation that triggers the issue, but (apparently?) any operation that
produces another join, such as filtering by an attribute in a related
model. In addition, the sentence "the annotation is computed over the
state of the query up to the point where the annotation is requested" is
misleading: A subsequent filter or additional aggregation can alter the
results of a previous one. It could help users if we added something like
"except for these cases <link to a generalized 'combining multiple
aggregations' section>".
Your suggested solution is not necessary in this case, simply filtering
before the annotation does work correctly as far as I could see:
{{{
# works as expected, sums the filtered books
Publisher.objects.filter(books__in=Books.objects.all()).annotate(Sum("books_pages"))
}}}
What does not work correctly is filtering the publishers by some property
of their books *after* the aggregation without affecting the aggregation:
{{{
# this alters the sum although the documentation suggests this should just
work
Publisher.objects.annotate(Sum("books_pages")).filter(books__in=Books.objects.all())
}}}
--
Ticket URL: <https://code.djangoproject.com/ticket/33403#comment:4>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-updates/064.97f063f361ff9de4f2560053ac20e16f%40djangoproject.com.