#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
-------------------------------------+-------------------------------------
Changes (by Simon Charette):

 * status:  new => closed
 * resolution:   => invalid


Comment:

 While the documentation doesn't explicit mention this particular
 combination you are effectively hitting #10060 where the `book` table is
 joined twice because instead of a single time and used for aggregation and
 filtering.

 In order to avoid this problem you can use a `FilteredRelation` alias or
 simply the `condition` argument of `Sum`

 {{{#!python
 Publisher.objects.annotate(Sum("books__pages",
 condition=Q(books__in=Book.objects.all()))

 Publisher.objects.alias(
     filtered_books=FilteredRelation("books",
 condition=Q(books__in=Book.objects.all()))
 ).annotate(
     Sum("filtered_books__pages"),
 )
 }}}

 Please TicketClosingReasons/UseSupportChannels in the future for this kind
 of questions

 ---

 I kind of wish we made `FiltereRelation(relation: str, condition: Q)`
 `Relation(relation: str, condition: Optional[Q])` instead and documented
 its usage to circumvent this problem with the use of `alias` to ''tell''
 the ORM a JOIN **must** be reused.

-- 
Ticket URL: <https://code.djangoproject.com/ticket/33403#comment:3>
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.fa22fe6b24e776ea753fa873668cab4d%40djangoproject.com.

Reply via email to