Django ORM 如何舍入平均结果 [英] Django ORM how to Round an Avg result
问题描述
我有一个模型,在该模型中我使用 Django ORM 从表中提取平均值.我想四舍五入那个 Avg 值,我该怎么做?
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?
见下文,我从按日期分组的价格模型中提取平均价格,格式为 YYYY-MM,我想自动提取四舍五入到最接近数字的平均值.
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')
推荐答案
使用 Func() 表达式.
这是使用 Django 聚合主题指南 在 SQLite 中四舍五入到两位小数:
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')))
这允许参数化轮函数(来自@RichardZschech 的回答):
This allows the round function to be parameterised (from @RichardZschech's answer):
class Round(Func):
function = 'ROUND'
arity = 2
Book.objects.all().aggregate(Round(Avg('price'), 2))
这篇关于Django ORM 如何舍入平均结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!