Get the latest filter entry in Django

I am trying to get the last object of the Django model, but cannot succeed.

None of them work:

obj = Model.objects.filter(testfield=12).latest() 
 obj = Model.objects.latest().filter(testfield=12) 
+65
python django django-models django-queryset
Mar 28 '13 at 6:37
source share
5 answers
 obj= Model.objects.filter(testfield=12).order_by('-id')[0] 
+76
Mar 28 '13 at 6:48
source share

See django docs: https://docs.djangoproject.com/en/dev/ref/models/querysets/#latest

You need to specify the field in the last (). eg.

 obj= Model.objects.filter(testfield=12).latest('testfield') 

Or, if your Meta models specify get_latest_by, you can leave the field_name argument to earliest() or latest() . By default, Django will use the field specified in get_latest_by .

+88
Feb 24 '14 at 3:31
source share

latest really designed to work with date fields (it probably also works with other totally ordered types, but not sure). And the only way you can use it without specifying a field name is to set the get_latest_by meta attribute, as mentioned here .

+15
Mar 28 '13 at 6:55
source share

last () last ()

Use the last ():

 ModelName.objects.last() 

using latest ():

 ModelName.objects.latest('id') 
+6
Sep 08 '17 at 7:12
source share

obj= Model.objects.filter(testfield=12).order_by('-id')[:1] is the right solution

+5
Jun 15 '17 at 19:13
source share



All Articles