Django: Aggregation, force Avg to return integer instead of decimal

Viewed 347

is there any way how can I replace this ugly stats['price_avg'] = round(stats['price_avg']) to a better solution? I tried using Round() ORM function, but this returns in X.0 format. What I need is only an integer without any decimals.

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'])

For example, right now I receive this API payload:

{
    "ads_total": 9,
    "price_min": 35,
    "price_avg": 426.1111111111111,
    "price_max": 1500
}

What I want:

{
    "ads_total": 9,
    "price_min": 35,
    "price_avg": 426,
    "price_max": 1500
}
1 Answers

You can use 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()),
)
Related