Reputation: 6831
I am using django 1.7.
I have field called priority
.
I want to find next high value and previous low value
for example if i have this in database
1,5,8,4,12,19,31
So for example if my current priority = 12
then i want to get record with priority 19
and previous with priority=8
I am not able to figure out how to do
Upvotes: 2
Views: 895
Reputation: 308799
To get the next object, first filter to get all objects with a higher priority:
objects = MyObjects.objects.filter(priority__gt=12)
then order the results by priority:
objects = objects.order_by('priority')
finally select the first item in the queryset:
next_obj = objects.first()
Putting it together:
next_obj = MyObjects.objects.filter(priority__gt=12).order_by('priority').first()
Getting the previous object is similar, but you need to order in reverse:
prev_obj = MyObjects.objects.filter(priority__lt=12).order_by('-priority').first()
Note that first()
can return None
if there are no objects in the queryset (in your case, that means the current object has the highest or lowest priority in the list). If the same priority can appear more than once, you might want to adjust the code to use gte
and lte
.
Upvotes: 5