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

34👍

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.

23👍

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]

4👍

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.

👤Dan

2👍

Be careful of using

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

as you might be indexing an empty QuerySet. I’m not sure what the correct Pythonic approach is, but the simplest would be to wrap it in an if/else or try/catch:

try:
    last = Edition.objects.order_by('-pub_date')[0]
except IndexError:
    # Didn't find anything...

But, as @Harley said, when you’re ordering by date, latest() is the djangonic way to do it.

👤Yogi

0👍

This has already been answered, but for more reference, this is what Django Book has to say about Slicing Data on QuerySets:

Note that negative slicing is not supported:

>>> Publisher.objects.order_by('name')[-1]
Traceback (most recent call last):
  ...
AssertionError: Negative indexing is not supported.

This is easy to get around, though. Just change the order_by()
statement, like this:

>>> Publisher.objects.order_by('-name')[0]

Refer the link for more such details. Hope that helps!

Leave a comment