Get the latest record with filter in Django


I am trying to get the latest Django model object but cannot seem to succeed.

Neither of these are working:

obj = Model.objects.filter(testfield=12).latest()
obj = Model.objects.latest().filter(testfield=12)
5/11/2019 10:38:54 PM

Accepted Answer

obj= Model.objects.filter(testfield=12).order_by('-id')[0]
3/28/2013 7:10:18 AM

See the docs from django:

You need to specify a field in latest(). eg.

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

Or if your model’s Meta specifies get_latest_by, you can leave off the field_name argument to earliest() or latest(). Django will use the field specified in get_latest_by by default.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow