#33477: Union Operator merges annotated values wrongfully
-------------------------------------+-------------------------------------
     Reporter:  Tobias Maschek       |                    Owner:  nobody
         Type:  Bug                  |                   Status:  closed
    Component:  Database layer       |                  Version:  4.0
  (models, ORM)                      |
     Severity:  Normal               |               Resolution:  invalid
     Keywords:  annotation,          |             Triage Stage:
  querysets, merging                 |  Unreviewed
    Has patch:  0                    |      Needs documentation:  0
  Needs tests:  0                    |  Patch needs improvement:  0
Easy pickings:  0                    |                    UI/UX:  0
-------------------------------------+-------------------------------------
Changes (by Mariusz Felisiak):

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


Comment:

 > Or do I use the union operator incorrectly?

 As far as I'm aware, yes. `|` combines two querysets using the SQL `OR`
 operator (see
 [https://docs.djangoproject.com/en/stable/ref/models/querysets/#or docs]),
 so in your case it creates:
 {{{#!python
 Employee.objects.filter(
     Q(shift__start__range=(monday, monday + timedelta(weeks=1)))
     |
     ~Q(shift__start__range=(monday, monday + timedelta(weeks=1)))
 ).annotate(total=Sum('shift__dur'))
 }}}

 You can use `filter` to get a
 [https://docs.djangoproject.com/en/stable/ref/models/conditional-
 expressions/#conditional-aggregation conditional aggregation], e.g.
 {{{#!python
 Employee.objects.annotate(total=Sum('shift__dur',
 filter=Q(shift__start__range=(monday, monday + timedelta(weeks=1)))))
 }}}

-- 
Ticket URL: <https://code.djangoproject.com/ticket/33477#comment:2>
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/062.d3f30fba95eeae96bad05c98ea30a804%40djangoproject.com.

Reply via email to