首页 > 解决方案 > 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
}

标签: pythondjangodjango-rest-framework

解决方案


您可以使用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()),
)

推荐阅读