viviwill viviwill - 3 months ago 29
Python Question

Django, division between two annotate result won't calculate correctly

I'm trying to get a division between two annotate results in queryset. Impression is much larger than click, so I should get tenth decimal.

def get_queryset(self):
return googleData.objects.filter(account=self.account_name).\
annotate(Sum('click'), Sum('impression'), Sum('converted_click'),
Sum('conversion_value'), Sum('cost'), Sum('conversion_value'), ctr_monthly= Sum('click')/Sum('impression')).\

Trouble here:

ctr_monthly= Sum('click')/Sum('impression'))

In template i have:

<td>{{ googleData.ctr_monthly | floatformat:2}} </td>

And the result is 0.00.
If I do ctr_final = click * impression, it generates correctly.
Click & Impression are both integerfield.

I tried use the float(), gave me a syntax error.

The other question is: what's the best pratice to make a queryset like this? Is there any way that I can break it down to several short piece of code and make it more neat and readable ?

Thank you~


As far as I am aware, there isn't a way to do this using the ORM.

The Sum() function returns the same field type as put into it (i.e. an IntegerField() will always return an Integer). You could use a function like ExpressionWrapper to force the output to be a float, but that won't help in this case as it will be too late: the division of two integers will have been already returning another integer.

To solve your problem, remove the ctr_monthly section form your query, and create a simple template tag which converts the two numbers to floats and divide them.

Your template will then look like: <td>{{ monthly_ctr(, googleData.impression) | floatformat:2}} </td>