arcee123
arcee123

Reputation: 211

DJango query based on value between two records

I have a table of records that has a name and a value. The table is arranged like this:

ID CLASS   MINIMUM
1  classA  1
2  classB  6
3  classC  10
4  classD  25

if given a number I am looking for the ID of the record under but closest to that number. For example, if I give you a 5, the system returns a 1. If I give you a 11, the system returns a 3.

Thanks

Upvotes: 0

Views: 103

Answers (1)

karthikr
karthikr

Reputation: 99620

How about this?

rand_number = 10 #Or any random number
min_obj = MyModel.objects.filter(minimum__lte=rand_number).order_by('-minimum').first()
id = min_obj.id if min_obj else None

Basically, order the column named minimum (or whatever) in descending order, and and get the first record - Note first() works only for django >= 1.6, and fetch the ID

Upvotes: 2

Related Questions