class ObjectRate(models.Model):
user = models.ForeignKey(User)
my_object = models.ForeignKey(Design)
rate = models.DecimalField(max_digits=2,decimal_places=1)
rate
可以设置为-1
(不喜欢)或1
(例如)。如何计算有多少是不喜欢的,有多少是喜欢的? (对于单个对象)
views.py:
def my_views(request,id):
my_object = Object.objects.get(id=id)
votes = ObjectRate.objects.filter(..)
使用什么“算法”?
答案 0 :(得分:5)
您可以按ObjectRate
和my_object
值(-1或1)过滤rate
并分别获取计数:
dislikes = ObjectRate.objects.filter(my_object__id=my_object.id, rate=-1).count()
likes = ObjectRate.objects.filter(my_object__id=my_object.id, rate=1).count()
答案 1 :(得分:0)
@Aamir答案很好。 但我建议您使用“related_name”
class ObjectRate(models.Model):
user = models.ForeignKey(User, related_name="rates")
my_object = models.ForeignKey(Design)
rate = models.DecimalField(max_digits=2,decimal_places=1)
然后在你看来:
def my_views(request,id):
my_object = User.objects.get(id=id)
like_votes = my_object.rates.filter(rate=1).count()
dislike_votes = my_object.rates.filter(rate=-1).count()
提示:
没有必要在django过滤器中使用“object__id”,只需使用该对象即可。 例如:
dislikes = ObjectRate.objects.filter(my_object=my_object, rate=-1).count()
likes = ObjectRate.objects.filter(my_object=my_object, rate=1).count()