Fix Python – Get the latest record with filter in Django

Question

Asked By – doniyor

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)

Now we will see solution for issue: Get the latest record with filter in Django


Answer

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

This question is answered By – catherine

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0