Just got to rewrite some logic I made sometime ago
I’m inneed of making some calculations for a Django model so I wanted to use the full power of the ORM, to make it much more efficient.
total2 resolve to
total3 will be
I need it to be a number.
model_queryset .values("A", "B") .annotate(total1=Sum("C")) .annotate(total2=Sum("D")) # If total1 or total2 == None, total3 == None .annotate(total3=F("total1") + F("total2"))
Checked Sum docs, saw it has a
defaultargument but only in Django >4.0.
I’m using Django 3.2
FieldError("Cannot compute Sum('<CombinedExpression: F() - F() ... >'): '<CombinedExpression: F(total_solicitados) - F() ... >' is an aggregate")
- Tried with
ExpressionWrapper, defining an
Same result as original problem.
.annotate(total3=ExpressionWrapper( F("total1") + F("total2"), output_field=IntegerField() ))
Maybe I’m overcomplicating the annotation but it seems really nice to be able to do this in just one query.
It’s also way less code than before, improving legibility.