views:

4614

answers:

4

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]
+12  A: 
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
+6  A: 

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]
insin
+2  A: 

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
+1  A: 

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