Get the latest record with filter in Django Get the latest record with filter in Django python python

Get the latest record with filter in Django


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

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.


obj= Model.objects.filter(testfield=12).order_by('-id')[0]


last() latest()

Usign last():

ModelName.objects.last()

using latest():

ModelName.objects.latest('id')