user2307683
user2307683

Reputation: 2029

How to count how many is dislike and how many is like?

class ObjectRate(models.Model):
    user = models.ForeignKey(User)
    my_object = models.ForeignKey(Design)
    rate = models.DecimalField(max_digits=2,decimal_places=1)

rate can be set to -1(dislike) or 1(like). How to count how many is dislike and how many is like? (for single object)

views.py:

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

What "algorithm" to use?

Upvotes: 0

Views: 668

Answers (2)

Leandro
Leandro

Reputation: 2247

The @Aamir answer is good. But i recommend you user "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)

then in Your view:

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()

tip:

is not necessary use "object__id" in django filter, just use the object. Example:

dislikes = ObjectRate.objects.filter(my_object=my_object, rate=-1).count()
likes = ObjectRate.objects.filter(my_object=my_object, rate=1).count()

Upvotes: 0

Aamir Rind
Aamir Rind

Reputation: 39689

You can filter ObjectRate by my_object and rate value (either -1 or 1) and get the counts separately:

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()

Upvotes: 5

Related Questions