Django ORM如何舍入平均结果 [英] Django ORM how to Round an Avg result

查看:288
本文介绍了Django ORM如何舍入平均结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型,我使用Django ORM从表中提取值的平均值。我想要回合这个平均值,我该怎么做?



看下面我从价格模型中提取平均价格,按日期格式YYYY-MM分组,我想自动提取四舍五入到最接近的数字的平均值。

  rs = Prices.objects.all.extra(select = {
'for_date':'CONCAT(CONCAT(extract(YEAR from for_date), - ),
LPAD(extract(MONTH from for_date),2,00))'
} ).values('for_date')。annotate(price = Avg('price'))。order_by(' - for_date')


解决方案

使用 Func ()表达式(自1.8以后可用)



以下是使用 Django聚合主题指南,在SQLite中舍入两位小数:

  class Round(Fun c):
function ='ROUND'
template ='%(function)s(%(表达式)s,2)'

Book.objects.all()聚合(Round(Avg('price')))


I have a model in which I use Django ORM to extract Avg of values from the table. I want to Round that Avg value, how do I do this?

See below I am extracting Avg price from Prices model grouped by date in format YYYY-MM, I want to automatically extract the average values rounded to the closest number.

rs = Prices.objects.all.extra(select={
    'for_date': 'CONCAT(CONCAT(extract( YEAR from for_date ), "-"),
        LPAD(extract(MONTH from for_date), 2, "00"))'
    }).values('for_date').annotate(price=Avg('price')).order_by('-for_date')

解决方案

Use Func() expressions (available since 1.8).

Here's an example using the Book model from Django Aggregation topic guide to round to two decimal places in SQLite:

class Round(Func):
    function = 'ROUND'
    template='%(function)s(%(expressions)s, 2)'

Book.objects.all().aggregate(Round(Avg('price')))

这篇关于Django ORM如何舍入平均结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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