Get the latest record in a query set

How can I get the latest entry in a specific query?

+56
django django-queryset
03 Feb 2018-10-02T00
source share
8 answers

You could just do something like this using reverse() :

 queryset.reverse()[0] 

Also, beware of this warning from the Django documentation:

... note that reverse() should usually only be called on a QuerySet that has a certain ordering (for example, when querying a model that defines the default order or when using order_by() ). If no such orders are defined for this QuerySet by calling reverse() , it has no real effect (the order is undefined until reverse() called, and then it will be undefined).

+60
Feb 03 2018-10-02T00
source share
— -

Django Doc :

latest(field_name=None) returns the last object in the table by date, using field_name provided as the date field.

This example returns the last record in the table, according to pub_date :

 Entry.objects.latest('pub_date') 
+92
Aug 23 2018-10-10T00:
source share

Django> = 1.6

Added methods QuerySet first () and last (), which are convenient methods that return the first or last object that matches the filters. Returns No if there are no matching objects.

+28
Jan 21 '14 at 1:14
source share

The easiest way to do this:

 books.objects.all().last() 

You can also use this for the first entry:

 books.objects.all().first() 
+19
Nov 13 '15 at 9:57
source share

To get the first object:

 ModelName.objects.first() 

To get the latest objects:

 ModelName.objects.last() 

You can use filter

 ModelName.objects.filter(name='simple').first() 

This works for me.

+11
Nov 25 '15 at 12:24
source share

Using django 1.6 and above is much easier now that a new api has been introduced -

 Model.object.earliest() 

It will give the last () in the opposite direction.

ps - I know his old question, I post as if going forward, someone lands on this question, they recognize this new function and do not end up using the old method.

+3
Jan 11 '14 at 21:16
source share

When the query set is already exhausted, you can do this to avoid another db hint -

 last = queryset[len(queryset) - 1] if queryset else None 

Do not use try...except...
Django does not throw an IndexError in this case.
It throws an AssertionError or ProgrammingError (when starting python with the -O option)

+3
May 14 '14 at 4:26
source share

The easiest way, without worrying about the current order, is to convert the QuerySet to a list so you can use standard Python negative indexing. For example:

 list(User.objects.all())[-1] 
-four
Feb 07 '13 at 15:14
source share



All Articles