如何汇总基于两列的计算平均值? [英] How to aggregate the average of a calculation based on two columns?

查看:228
本文介绍了如何汇总基于两列的计算平均值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个Django查询来给我表中所有行的平均值.我的模特看起来像

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=0, max_digits=12, decimal_places=2)
    num_articles = models.IntegerField(default=0)
    day_of_week = IntegerField(
        null=True,
        validators=[
            MaxValueValidator(6),
            MinValueValidator(0)
        ]
    )

然后我尝试像这样计算平均值

and I attempt to calculate the average like this

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

但这会导致错误

  File "/Users/davea/Documents/workspace/mainsite_project/venv/lib/python3.7/site-packages/django/db/models/query.py", line 362, in aggregate
    raise TypeError("Complex aggregates require an alias")
TypeError: Complex aggregates require an alias

计算平均值的正确方法是什么?

What's the right way to calculate the average?

推荐答案

您不需要Func进行划分,但需要协调两种不同的字段类型.使用 ExpressionWrapper Avg:

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 import ExpressionWrapper

everything_avg = (StatByDow.objects
    .aggregate(avg=ExpressionWrapper(
        Avg(F('total_score') / F('num_articles')),
        DecimalField()
    ))
)

您还可以使用从整数到小数的Cast(不适用于PostgreSQL,该对象遵循Django的语法::numeric(NONE, NONE))或围绕除法的ExpressionWrapper,但是最后一个ExpressionWrapper最快解决方案,因为它最后只发生一次.

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.

这篇关于如何汇总基于两列的计算平均值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆