Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i order by a calculated field complex in Django?

I have a model like this:

class Program(models.Model):
    votes_sum = models.IntegerField(max_length=10, default=0)
    voters_counter = models.IntegerField(max_length=10, default=0)
    ...

I need the 10 best rated programs, so, I've tried in my views.py:

best_rated = Program.objects.filter(Q(creator__profile__type = 'us')).extra(select={ 'total' : 'votes_sum / voters_counter' }).extra(order_by=['total'])[:10]

The problem is when no users have voted, because division by zero occurs.

I could not find another way to solve this. Any help? Please.


I have a simpler solution than I thought. Simply exclude records with no votes!

best_rated = Program.objects.filter(Q(creator__profile__type = 'us') & ~Q(voters_counter = 0)).extra(select={ 'total' : 'votes_sum / voters_counter' }).extra(order_by=['total'])[:10]

like image 496
Joeya Avatar asked Feb 28 '11 20:02

Joeya


1 Answers

You could try to make a loop in your view that would be something like:

if ZeroDivisionError: 
    total = 0

this is just a starting point, but hopefully it helps

edit: this may be better

try:
    total = votes_sum / voters_count
except ZeroDivisionError:
    total = 0
return total
like image 126
j_syk Avatar answered Nov 15 '22 05:11

j_syk