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]
- [Django]-Python 3 list(dictionary.keys()) raises error. What am I doing wrong?
- [Django]-PHP Frameworks (CodeIgniter, Yii, CakePHP) vs. Django
- [Django]-How do you detect a new instance of the model in Django's model.save()
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.
- [Django]-How do I install psycopg2 for Python 3.x?
- [Django]-Passing STATIC_URL to file javascript with django
- [Django]-Nginx doesn't serve static
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.
- [Django]-Why won't Django use IPython?
- [Django]-How to pass django rest framework response to html?
- [Django]-Specifying limit and offset in Django QuerySet wont work
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!
- [Django]-How do you detect a new instance of the model in Django's model.save()
- [Django]-How do I install psycopg2 for Python 3.x?
- [Django]-Passing STATIC_URL to file javascript with django