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