我如何在 Django 中按计算字段复合体进行排序?
我有一个这样的模型:
class Program(models.Model):
votes_sum = models.IntegerField(max_length=10, default=0)
voters_counter = models.IntegerField(max_length=10, default=0)
...
我需要 10 个评价最高的程序,所以,我在 view.py 中尝试过:
best_erated = Program.objects.filter(Q(creator__profile__type = 'us')).extra(select={ 'total' : 'votes_sum / voters_counter' }).extra(order_by=['total'])[: 10]
]问题是当没有用户投票时,因为会发生除数为零的情况。
我找不到其他方法来解决这个问题。有什么帮助吗?请。
我有一个比我想象的更简单的解决方案。只需排除没有投票的记录即可!
best_erated = Program.objects.filter(Q(creator__profile__type = 'us') & ~Q(voters_counter = 0)).extra(select={ 'total' : 'votes_sum / voters_counter' }).extra(order_by =['总计'])[:10]
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]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以尝试在您的视图中创建一个循环,如下所示:
这只是一个起点,但希望它能帮助
编辑:这可能会更好
You could try to make a loop in your view that would be something like:
this is just a starting point, but hopefully it helps
edit: this may be better