0
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(喜欢)。如何计算有多少不喜欢,有多少喜欢?(对于单个对象)

视图.py:

def my_views(request,id):
    my_object = Object.objects.get(id=id)
    votes = ObjectRate.objects.filter(..)

使用什么“算法”?

4

2 回答 2

5

ObjectRate您可以按值(-1 或 1)过滤my_object并分别获取计数: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()
于 2013-06-17T14:37:58.023 回答
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()
于 2013-06-17T19:11:39.837 回答