In django, how do I sort a model on a field and then get the last item? In django, how do I sort a model on a field and then get the last item? django django

In django, how do I sort a model on a field and then get the last item?


obj = Edition.objects.latest('pub_date')

You can also simplify things by putting get_latest_by in the model's Meta, then you'll be able to do

obj = Edition.objects.latest()

See the docs for more info. You'll probably also want to set the ordering Meta option.


Harley's answer is the way to go for the case where you want the latest according to some ordering criteria for particular Models, as you do, but the general solution is to reverse the ordering and retrieve the first item:

Edition.objects.order_by('-pub_date')[0]


Note:

Normal python lists accept negative indexes, which signify an offset from the end of the list, rather than the beginning like a positive number. However, QuerySet objects will raise

AssertionError: Negative indexing is not supported.
if you use a negative index, which is why you have to do what insin said: reverse the ordering and grab the 0th element.