I am trying to get the latest django model object but cannot seem to succeed.
neither
obj= Model.objects.filter(testfield=12).latest()
nor
obj= Model.objects.latest().filter(testfield=12)
is working.
please help.
I am trying to get the latest django model object but cannot seem to succeed.
neither
obj= Model.objects.filter(testfield=12).latest()
nor
obj= Model.objects.latest().filter(testfield=12)
is working.
please help.
latest
is really designed to work with date fields (it probably does work with other total-ordered types too, but not sure). And the only way you can use it without specifying the field name is by setting theget_latest_by
meta attribute, as mentioned here.obj= Model.objects.filter(testfield=12).order_by('-id')[:1]
is the right solutionlast() latest()
Usign last():
using latest():
See the docs from django: https://docs.djangoproject.com/en/dev/ref/models/querysets/#latest
You need to specify a field in latest(). eg.
Or if your model’s Meta specifies get_latest_by, you can leave off the
field_name
argument toearliest() or latest()
. Django will use the field specified inget_latest_by
by default.