django-ratings
django-ratings copied to clipboard
Not setting weight causes division by zero when calculating average (Postgres)
When I'm developing locally, I can leave the weight as default (0) and not get any errors when calculating the average rating using qs.extra()
. However on a production server with Postgres this causes a 'Division by Zero' database error. I think this only happens when rating_votes+Recipe.rating.range
is zero. I worked around this by setting the weight to 1.
Great! Thanks for the advise - it saved me from a lot of trouble! I couldn't find a easy solution to the problem and didn't think of looking at something as obvious as the weight.
Unfortunately if you have existing ratings before you notice/fix this issue, setting weight=1
will alter the ordering of ratings, in a way that for me made my sorting appear broken.
The other option is to use a case statement in the extra query.
Here is my code, I'm not getting the % of approval like the documentation example, this just orders by the avg rating expressed as a float. This allows you to not use the weight as a fix and keep your existing ratings. You'll need to use a template tag/filter to format the avg_rating
for display.
qs = qs.extra(select={'avg_rating': 'case when rating_votes = 0 then 0 else ((rating_score)/(rating_votes+%d)) end' % (MyModel.rating.weight)})
I think the example in the documentation would be better with the case statement added.