How To Aggregate The Average Of A Calculation Based On Two Columns?
I want to write a Django query to give me the average across all rows in my table. My model looks like class StatByDow(models.Model): total_score = models.DecimalField(default=
Solution 1:
You don't need Func
for the division, but you need to reconcile the two different field types. Use an ExpressionWrapper around Avg
:
from django.db.models importExpressionWrappereverything_avg= (StatByDow.objects
.aggregate(avg=ExpressionWrapper(
Avg(F('total_score') / F('num_articles')),
DecimalField()
))
)
You could also use a Cast
from integer to decimal (not with PostgreSQL, which objects to Django's syntax ::numeric(NONE, NONE)
) or an ExpressionWrapper
around the division, but just one ExpressionWrapper
at the end is the quickest solution as it happens once at the end.
Post a Comment for "How To Aggregate The Average Of A Calculation Based On Two Columns?"