Skip to content
This repository has been archived by the owner on Jul 17, 2018. It is now read-only.

Not setting weight causes division by zero when calculating average (Postgres) #10

Open
TimFletcher opened this issue Aug 24, 2010 · 2 comments

Comments

@TimFletcher
Copy link

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.

@tmpethick
Copy link

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.

@rudedogg
Copy link

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.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants