'Django dictionary for annotations works or not depending on the order of the most complex annotation and/or the aliases of the other annotations
So I came across this issue described in the title of this post.
I have this dynamically created dictionary:
dict= {'sale_qty': Sum('sale_qty'), 'sales_override': Sum(F('sales_override')), 'colab_ventas': Sum(F('colab_ventas')), 'Historia Ajustada': Sum(Case(When(sales_override=None, then=F('sale_qty')),When(sales_override__gte=0, then=F('sales_override'))))}
This is the query: Venta.objects.values('item').annotate(**dict)
and when I try to run it, it fails with error:
Exception Type: FieldError Exception Value: Cannot compute Sum('<Case: CASE WHEN <Q: (AND: ('sales_override', None))> THEN F(sale_qty), WHEN <Q: (AND: ('sales_override__gte', 0))> THEN F(sales_override), ELSE Value(None)>'): '<Case: CASE WHEN <Q: (AND: ('sales_override', None))> THEN F(sale_qty), WHEN <Q: (AND: ('sales_override__gte', 0))> THEN F(sales_override), ELSE Value(None)>' is an aggregate
BUT if I change the order of the elements in the dictionary moving the complex annotation 'Historia Ajustada' to the beggining it works just fine:
dict= {'Historia Ajustada': Sum(Case(When(sales_override=None, then=F('sale_qty')),When(sales_override__gte=0, then=F('sales_override')))),'sale_qty': Sum('sale_qty'), 'sales_override': Sum(F('sales_override')), 'colab_ventas': Sum(F('colab_ventas')) }
It also works fine if I keep the original order of the dictionary and change the aliases of the simple annotations like this (for example adding a '1' to the alias):
dict= {'sale_qty1': Sum('sale_qty'), 'sales_override1': Sum(F('sales_override')), 'colab_ventas1': Sum(F('colab_ventas')), 'Historia Ajustada': Sum(Case(When(sales_override=None, then=F('sale_qty')),When(sales_override__gte=0, then=F('sales_override'))))}
What could be the cause of this ? Is this a django bug or expected behaviour?
I have to give special treatment to some parts of the code because of this.
Thanks.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
