Reputation: 37876
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)
Upvotes: 133
Views: 197635
Reputation: 551
obj = Model.objects.filter(testfield=12).order_by('id').latest('id')
Model.objects.filter(testfield=12)
Now, order the results base on your primary key - most of the times the pk=id
Model.objects.filter(testfield=12).order_by('id')
https://docs.djangoproject.com/en/4.0/ref/models/querysets/#order-by
By default, results returned by a QuerySet are ordered by the ordering tuple given by the ordering option in the model’s Meta. You can override this on a per-QuerySet basis by using the order_by method.
Model.objects.filter(testfield=12).order_by('id').latest('id')
Upvotes: 4
Reputation: 582
You can do comparison with this down here.
latest('created')
is same as order_by('-created').first()
Please correct me if I am wrong
Upvotes: 3
Reputation: 1232
Usign last():
ModelName.objects.last()
using latest():
ModelName.objects.latest('id')
Upvotes: 64
Reputation: 2188
obj= Model.objects.filter(testfield=12).order_by('-id')[:1]
is the right solution
Upvotes: 7
Reputation:
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.
Upvotes: 165