I was googling about this and there is a simplier way which uses Cast
but then thing is I believe that's for django 2.0
that mine is django 1.9
I found a post and I tried it, it doesn't really work for me though.
Let's say I have a model with value
and max
fields. I want to get the sum of all value
and max
then divide them to get the average. What I did just gets one row and return the avg of the row, can someone let me know what I have been doing wrong here?
model_calcuation = Model.objects.filter().annotate(
sum_score=Sum('value', output_field=FloatField()),
sum_max=Sum('max', output_field=FloatField())
).annotate(
avg=F('sum_score') / F('sum_max')
)
Thanks in advance for any help
If I understood correctly your question, you are looking for aggregate()
operation.
from django.db.models import F, Sum
model_calcuation = Model.objects.aggregate(result=Sum(F('value')) / Sum(F('max')))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.