99π
EDIT : You now have to use Entry.objects.latest('pub_date')
You could simply do something like this, using reverse()
:
queryset.reverse()[0]
Also, beware this warning from the Django documentation:
β¦ note that
reverse()
should
generally only be called on a QuerySet
which has a defined ordering (e.g.,
when querying against a model which
defines a default ordering, or when
usingorder_by()
). If no such ordering
is defined for a givenQuerySet
,
callingreverse()
on it has no real
effect (the ordering was undefined
prior to callingreverse()
, and will
remain undefined afterward).
170π
latest(field_name=None)
returns the latest object in the table, by date, using the field_name provided as the date field.This example returns the latest Entry in the table, according to the
pub_date
field:Entry.objects.latest('pub_date')
- [Django]-How to add new languages into Django? My language "Uyghur" or "Uighur" is not supported in Django
- [Django]-Problems with contenttypes when loading a fixture in Django
- [Django]-.filter() vs .get() for single object? (Django)
82π
The simplest way to do it is:
books.objects.all().last()
You also use this to get the first entry like so:
books.objects.all().first()
- [Django]-In Django 1.4, do Form.has_changed() and Form.changed_data, which are undocumented, work as expected?
- [Django]-Create empty queryset by default in django form fields
- [Django]-Can't compare naive and aware datetime.now() <= challenge.datetime_end
48π
To get First object:
ModelName.objects.first()
To get last objects:
ModelName.objects.last()
You can use filter
ModelName.objects.filter(name='simple').first()
This works for me.
- [Django]-ValueError: The field admin.LogEntry.user was declared with a lazy reference
- [Django]-A field with precision 10, scale 2 must round to an absolute value less than 10^8
- [Django]-Handle `post_save` signal in celery
37π
Django >= 1.6
Added QuerySet methods first() and last() which are convenience methods returning the first or last object matching the filters. Returns None if there are no objects matching.
- [Django]-Django templates: verbose version of a choice
- [Django]-Combining Django F, Value and a dict to annotate a queryset
- [Django]-What is the SQL ''LIKE" equivalent on Django ORM queries?
8π
When the queryset is already exhausted, you may do this to avoid another db hint β
last = queryset[len(queryset) - 1] if queryset else None
Donβt use try...except...
.
Django doesnβt throw IndexError
in this case.
It throws AssertionError
or ProgrammingError
(when you run python with -O option)
- [Django]-Django.db.utils.ProgrammingError: relation already exists
- [Django]-Python (and Django) best import practices
- [Django]-Does SQLAlchemy have an equivalent of Django's get_or_create?
5π
You can use Model.objects.last()
or Model.objects.first()
.
If no ordering
is defined then the queryset is ordered based on the primary key. If you want ordering behaviour queryset then you can refer to the last two points.
If you are thinking to do this, Model.objects.all().last()
to retrieve last and Model.objects.all().first()
to retrieve first element in a queryset or using filters
without a second thought. Then see some caveats below.
The important part to note here is that if you havenβt included any ordering
in your model the data can be in any order and you will have a random last or first element which was not expected.
Eg. Letβs say you have a model named Model1
which has 2 columns id
and item_count
with 10 rows having id 1 to 10.[Thereβs no ordering defined]
If you fetch Model.objects.all().last() like this, You can get any element from the list of 10 elements. Yes, It is random as there is no default ordering.
So what can be done?
- You can define
ordering
based on any field or fields on your model. It has performance issues as well, Please check that also. Ref: Here - OR you can use
order_by
while fetching.
Like this:Model.objects.order_by('item_count').last()
- [Django]-Add a custom button to a Django application's admin page
- [Django]-Django JSONField inside ArrayField
- [Django]-Getting Django admin url for an object
4π
If using django 1.6 and up, its much easier now as the new api been introduced β
Model.object.earliest()
It will give latest() with reverse direction.
p.s. β I know its old question, I posting as if going forward someone land on this question, they get to know this new feature and not end up using old method.
- [Django]-Is it secure to store passwords as environment variables (rather than as plain text) in config files?
- [Django]-What is a django.utils.functional.__proxy__ object and what it helps with?
- [Django]-Python Django Rest Framework UnorderedObjectListWarning
- [Django]-Django admin file upload with current model id
- [Django]-How can I create a deep clone of a DB object in Django?
- [Django]-Django test app error β Got an error creating the test database: permission denied to create database
1π
If you use ids with your models, this is the way to go to get the latest one from a qs.
obj = Foo.objects.latest('id')
- [Django]-Cron and virtualenv
- [Django]-Django-celery: No result backend configured
- [Django]-What is the SQL ''LIKE" equivalent on Django ORM queries?
0π
In a Django template I had to do something like this to get it to work with a reverse queryset:
thread.forumpost_set.all.last
Hope this helps someone looking around on this topic.
- [Django]-Django check if a related object exists error: RelatedObjectDoesNotExist
- [Django]-Django TypeError: 'RelatedManager' object is not iterable
- [Django]-How to use subquery in django?
- [Django]-How can I build multiple submit buttons django form?
- [Django]-Sending post data from angularjs to django as JSON and not as raw content
- [Django]-TransactionManagementError "You can't execute queries until the end of the 'atomic' block" while using signals, but only during Unit Testing
-8π
The simplest way, without having to worry about the current ordering, is to convert the QuerySet to a list so that you can use Pythonβs normal negative indexing. Like so:
list(User.objects.all())[-1]
- [Django]-Celery : Execute task after a specific time gap
- [Django]-What are the limitations of Django's ORM?
- [Django]-TypeError: data.forEach is not a function