#34551: Case-When aggregation over aggregated fields doesn't work since 4.2
-------------------------------------+-------------------------------------
               Reporter:  Denis      |          Owner:  nobody
  Roldán                             |
                   Type:  Bug        |         Status:  new
              Component:  Database   |        Version:  4.2
  layer (models, ORM)                |       Keywords:  orm, aggregate,
               Severity:  Normal     |  case, when, field error, bug
           Triage Stage:             |      Has patch:  0
  Unreviewed                         |
    Needs documentation:  0          |    Needs tests:  0
Patch needs improvement:  0          |  Easy pickings:  0
                  UI/UX:  0          |
-------------------------------------+-------------------------------------
 This same QuerySet was working on 4.1.X and prior versions and stopped
 working on 4.2.X:


 {{{
 annotated_users  = users_qs.annotate(
             total_things=Subquery(
 OtherModel.objects.filter(user_id=OuterRef("pk")).annotate(
                     total_objs=F("total")
                 ).values("total_objs")
             )
 )

 annotated_users.aggregate(
             sum_total_objs=Sum("total_things"),
             avg_conversion_rate=Case(
                 When(
                     sum_total_objs=0,
                     then=0,
                 ),
                 default=Round(
                     (Sum("sum_total_confirmed_objs") /
 Sum("sum_total_objs")) * 100, 2
                 ),
                 output_field=FloatField(),
             )
 )
 }}}

 As you can see `sum_total_objs` is an aggregated field that is also used
 on a second field to calculate the conversion rate. To avoid a zero
 division problem, we were using a Case-When clause over that field. It
 works well on any 4.1 and prior versions but stopped working since 4.2,
 raising a `FieldError` like:

 `Cannot resolve keyword 'sum_total_objs' into field`

 Thanks for the support!

-- 
Ticket URL: <https://code.djangoproject.com/ticket/34551>
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/01070187ffe6259c-869fd94a-bd34-43ca-8286-726858577fba-000000%40eu-central-1.amazonses.com.

Reply via email to