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.
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.
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.
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".
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]
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()))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With