django - get the latest record with filter

2019-01-13 14:15发布

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.

5条回答
Bombasti
2楼-- · 2019-01-13 14:56

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 the get_latest_by meta attribute, as mentioned here.

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-01-13 15:05

obj= Model.objects.filter(testfield=12).order_by('-id')[:1] is the right solution

查看更多
爷、活的狠高调
4楼-- · 2019-01-13 15:05

last() latest()

Usign last():

ModelName.objects.last()

using latest():

ModelName.objects.latest('id')
查看更多
Explosion°爆炸
5楼-- · 2019-01-13 15:21

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.

查看更多
Summer. ? 凉城
6楼-- · 2019-01-13 15:22
obj= Model.objects.filter(testfield=12).order_by('-id')[0]
查看更多
登录 后发表回答