Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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] 
like image 582
Paul Wicks Avatar asked Oct 31 '08 00:10

Paul Wicks


People also ask

How do I get most recent record in Django?

You need to specify a field in latest(). eg. Or if your model's Meta specifies get_latest_by, you can leave off the field_name argument to earliest() or latest() . Django will use the field specified in get_latest_by by default.

What is Order_by in Django?

For example: Entry. objects. order_by('blog__name', 'headline') If you try to order by a field that is a relation to another model, Django will use the default ordering on the related model, or order by the related model's primary key if there is no Meta.ordering specified.


2 Answers

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.

like image 180
Harley Holcombe Avatar answered Sep 30 '22 23:09

Harley Holcombe


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] 
like image 41
Jonny Buchanan Avatar answered Sep 30 '22 23:09

Jonny Buchanan