开发者

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

开发者 https://www.devze.com 2023-02-14 03:49 出处:网络
I have a model like this: class Program(models.Model): votes_sum = models.IntegerField(max_length=10, default=0)

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' }).开发者_Python百科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
0

精彩评论

暂无评论...
验证码 换一张
取 消