Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round Avg() to nearest integer? django

I have this in my views.py:

user_list = User.objects.select_related().annotate(rating=Avg('userrating__rating')).order_by('-rating')[:5]

And I want to round the Avg so I have nice round numbers for a rating.

However, if I use int(Avg('userrating__rating')))

it says:

int() argument must be a string or a number, not 'Avg'

if I use round(Avg('userrating__rating')) it says:

TypeError at / a float is required

same for math.ceil or math.floor

seems like a straight forward thing but I don't know how to do it. Thank you.

like image 860
Seif Avatar asked Mar 11 '16 16:03

Seif


People also ask

How do you round a number to the nearest integer in Python?

Python has a built-in round() function that takes two numeric arguments, n and ndigits , and returns the number n rounded to ndigits . The ndigits argument defaults to zero, so leaving it out results in a number rounded to an integer.

How do you round a variable in Python?

Python does have two methods that let you round up and down. The floor() method rounds down to the nearest integer. ceil() rounds up to the nearest integer.

How do you round down a number in Python?

The truncate method, also known as trunc(), is a built-in method of the math module. This method returns the integer part of a given decimal number. trunc(), as the name implies, shortens the number rather than rounding it up. Sometimes truncating the number is a better solution for "Round Down in Python".


2 Answers

You can also use Func() expressions

from django.db.models import Func
class Round(Func):
    function = 'ROUND'
    template='%(function)s(%(expressions)s, 0)'

user_list = User.objects.select_related().annotate(rating=Round(Avg('userrating__rating'))).order_by('-rating')[:5]
like image 70
ilse2005 Avatar answered Oct 18 '22 12:10

ilse2005


You can just cast it to an IntegerField.

from django.db.models import IntegerField

user_list = User.objects.select_related().annotate(
    rating=Avg('userrating__rating', output_field=IntegerField()))
like image 27
Antoine Pinsard Avatar answered Oct 18 '22 12:10

Antoine Pinsard