[Answered ]-Django – query for the closest numeric value to a given value

2👍

I don’t think your SQL is correct. It should return ‘level 3’ if the parameter is 1999. Based on your description the SQL could be:

SELECT pointsRequired FROM the_table WHERE pointsRequired < parameter ORDER BY pointsRequired DESC LIMIT 1;

Or in Django:

try:
    Level.objects.filter(requiredPoints__lt=parameter).order_by('-requiredPoints')[0]
except IndexError: 
    # Do something

Leave a comment