How can I retrieve the last record in a certain queryset?
How can I retrieve the last record in a certain queryset?
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).
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?
ordering based on any field or fields on your model. It has performance issues as well, Please check that also. Ref: Hereorder_by while fetching.
Like this: Model.objects.order_by('item_count').last()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.
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')