[Fixed]-Django order by integer value, not string value of choices field

1👍

You shouldn’t rely on changing database data to adapt to the way you want to display in the template. If you sort on a CharField that contains integer strings, it would only sort on lexicographic order, which is not what you want, like 21 is smaller than 3 because 3 is larger by comparing the first digit.

The solution is not that hard, just change avg_rating to IntegerField or better, DecimalField, which is specialized in dealing with human readable numbers. If you want to add something fancy in template, you could always write a custom template tag to show extra stuff around the numbers.

Read python doc about what is Decimal, and read django doc about how to create custom template tag.

Leave a comment