I have some Django model objects with different rating field values:
puzzles_rating = [0, 123, 245, 398, 412, 445, 556, 654, 875, 1000]
for rating in puzzles_rating:
puzzle = Puzzle(rating=rating)
puzzle.save()
Now, for a user_rating = 500, I want to choose a puzzle with the closest ranking match. In the above case, it should be puzzle number 6 with a rating of 445.
The problem is that I cannot just do:
puzzle = Puzzle.objects.filter(rating__lte=user_rating).order_by('-rating')[0]
since, as a rule, my closest rating may be greater than the target rating.
Is there a convenient way to request the closest match from both directions?
source
share