Reputation: 25
class Test(models.Model):
quantity = models.IntegerField()
How to retrieve an object whose "quantity" is the fifth(from the highest) in term of value?
Upvotes: 0
Views: 133
Reputation: 1122
If you want the fifth item:
t = Test.objects.order_by('-quantity')[4]
(the index starts at 0, so 4 refers to the 5th element)
order_by
is quite self explanatory, note the -
which order the queryset from the highest to the lowest.
You could try as well
t = Test.objects.order_by('quantity')[-5]
The order is reverse, and you take the 5th last element.
To ensure, the 5th element exist, you may had:
if Test.objects.all().count() >= 5:
t = Test.objects.order_by('-quantity')[4]
else:
pass # do something
Upvotes: 3