Question

Specifically, I have a model that has a field like this

pub_date = models.DateField("date published")

I want to be able to easily grab the object with the most recent pub_date. What is the easiest/best way to do this?

Would something like the following do what I want?

Edition.objects.order_by('pub_date')[:-1]
Was it helpful?

Solution

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.

OTHER TIPS

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.

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.

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!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top