Skip to content Skip to sidebar Skip to footer

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.

Solution 2:

you need to pass a name of an alias (obviously by the error text) for aggregate function. the query should be something like this:

everything_avg = StatByDow.objects.all().aggregate(avg_f=Avg(Func(F('total_score') / F('num_articles'))))

Post a Comment for "How To Aggregate The Average Of A Calculation Based On Two Columns?"