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]
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.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With