Reputation: 646
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.
Upvotes: 8
Views: 4833
Reputation: 11429
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]
Upvotes: 11
Reputation: 34942
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()))
Upvotes: 8
Reputation: 25539
You shouldn't try to wrap any conversion function on original orm call, because non of what you tried is valid django api. But you could always convert the number after you got the results:
for user in user_list:
user.rating = int(user.rating)
Upvotes: 2