Question

models.py

class Restaurant(models.Model)
    food_rating = RatingField(range=2, weight=5,can_change_vote = True,allow_delete = True,allow_anonymous = True)
    service_rating = RatingField(range=2, weight=5,can_change_vote = True,allow_delete = True,allow_anonymous = True)
    ambience_ratiing = RatingField(range=2, weight=5,can_change_vote = True,allow_delete = True,allow_anonymous = True)

view.py code

r = Restaurant.objects.get(pk=1)
r.food_rating.add(score = -1 , user = request.user , ip_address =request.META.get('HTTP_REFERER'))
print r.food_rating.score

error

djangoratings.exceptions.InvalidRating: -1 is not a valid choice for food_rating

doubt

my food_rating field is eligible to take two scores , how am i supposed to change the score so that i can implement vote up and vote down feature , on vote up , i should be able to add 1 to the existing score and on vote down i should be able to subtract a vote , please help , thanks in advance

Was it helpful?

Solution

The problem comes from this script:

if score < 0 or score > self.field.range:
    raise InvalidRating("%s is not a valid choice for %s" % (score, self.field.name))

Short answer: convert the [-x:y] interval you want to use for display, into [-x+x:y+x] in your code to avoid this problem. If you wanted [-5:5], then use [-5+5:5+5] which is [0:10]. If you wanted [-50:100] then use [-50+50:100+50] = [0:150] and so on ... It's a simple formula, that shouldn't be a problem for a programer ;)

Long answer: either you fork djangoratings, either you open an issue asking to add a setting enabling negative ratings ... and probably he'll reject it, because of the simple interval conversion workaround, here's some more concrete examples:

class Restaurant(models.Model):
    # blabla :)

    ambience_rating = RatingField(range=5, weight=5,can_change_vote = True,allow_delete = True,allow_anonymous = True)

    def get_adjusted_ambiance_rating(self):
        return self.ambience_rating - 3

So, if ambience_rating is "1" (the lowest score), get_adjusted_ambiance_rating() will return -2.

If ambience_rating is "5" (the highest score), get_ambiance_rating_with_negative() will return 2.

Adapt this example/trick to your needs.

You should probably make a single method for all ratings:

def get_adjusted_rating(self, which):
    return getattr(self, '%s_rating' % which) - 3

Callable as such:

restaurant.get_adjusted_rating('ambiance')
restaurant.get_adjusted_rating('food')

# etc ...

And maybe a template filter:

@register.filter
def get_adjusted_rating(restaurant, which):
    return restaurant.get_adjusted_rating(which)

Usable as such:

{{ restaurant|get_adjusted_rating:"ambiance" }}
{{ restaurant|get_adjusted_rating:"food" }}

{# etc, etc #}

More details about template filters.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top