Django Aggregate- Division with Zero Values -
i using django's aggregate query expression total values. final value division expression may feature 0 denominator. need way escape if case, returns 0.
i've tried following, i've been using similar annotate expressions:
from django.db.models import sum, f, floatfield, case, when def for_period(self, start_date, end_date): return self.model.objects.filter( date__range=(start_date, end_date) ).aggregate( sales=sum(f("value")), purchase_cogs=sum(f('purchase_cogs')), direct_cogs=sum(f("direct_cogs")), profit=sum(f('profit')) ).aggregate( margin=case( when(sales=0, then=0), default=(sum(f('profit')) / sum(f('value')))*100 ) )
however, doesn't work, because error says:
'dict' object has no attribute 'aggregate'
what proper way handle this?
this not work; because aggregate
returns dictionary, not queryset (see docs), can't chain 2 aggregate
calls together.
i think using annotate
solve issue. annotate
identical aggregate
, except in returns queryset results saved attributes rather return dictionary. result can chain annotate
calls, or call annotate
aggregate
.
so believe like:
return self.model.objects.filter( date__range=(start_date, end_date) ).annotate( # call `annotate` sales=sum(f("value")), purchase_cogs=sum(f('purchase_cogs')), direct_cogs=sum(f("direct_cogs")), profit=sum(f('profit')) ).aggregate( # `aggregate` margin=case( when(sales=0, then=0), default=(sum(f('profit')) / sum(f('value')))*100 ) )
should work.
hope helps.
Comments
Post a Comment