python - Django:聚合,强制平均返回整数而不是小数
问题描述
有什么办法可以将其替换ugly stats['price_avg'] = round(stats['price_avg'])
为更好的解决方案吗?我尝试使用Round() ORM 函数,但这以X.0格式返回。我需要的只是一个没有任何小数的整数。
stats = Ad.objects.aggregate(
ads_total=Count('pk'),
price_min=Coalesce(Min('price'), Val(0)),
price_avg=Coalesce(Avg('price'), Val(0.0)),
price_max=Coalesce(Max('price'), Val(0)),
)
stats['price_avg'] = round(stats['price_avg'])
例如,现在我收到了这个 API 有效负载:
{
"ads_total": 9,
"price_min": 35,
"price_avg": 426.1111111111111,
"price_max": 1500
}
我想要的是:
{
"ads_total": 9,
"price_min": 35,
"price_avg": 426,
"price_max": 1500
}
解决方案
您可以使用cast()
:
from django.db.models import IntegerField
from django.db.models.functions import Cast
stats = Ad.objects.aggregate(
ads_total=Count('pk'),
price_min=Cast(Coalesce(Min('price'), Val(0)), output_field=IntegerField()),
price_avg=Cast(Coalesce(Avg('price'), Val(0.0)), output_field=IntegerField()),
price_max=Cast(Coalesce(Max('price'), Val(0)), output_field=IntegerField()),
)
推荐阅读
- r - 如何更正产生差异的初始值 NA
- asp.net - AWS Elastic Beanstalk .NET App 的文件在上传和部署后没有改变
- java - java.lang.IllegalStateException:无法将节点从一个状态树移动到另一个状态树 - Vaadin
- ruby-on-rails - 通过域名(AWS EC2、Cloudflare)使 Rails Server 端口 3000 可访问
- powershell - ForEach-Object -Parallel 参数集无法解析
- javascript - 节点类启动函数
- go-templates - 无法将 readFile 的输出转换为 List 进行迭代
- python - 在单个数据库上使用 flask-migrate 创建具有不同架构的多个表
- excel - 提取第一个 Google 结果 URL -“运行时错误 '424':需要对象”
- php - 从 Android Studio 中的 MySQL 数据库获取连接的用户信息