Get the latest record with filter in Django

你说的曾经没有我的故事 提交于 2019-12-17 15:28:02

问题


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)

回答1:


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



回答2:


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.




回答3:


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.




回答4:


last() latest()

Usign last():

ModelName.objects.last()

using latest():

ModelName.objects.latest('id')



回答5:


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



来源:https://stackoverflow.com/questions/15675672/get-the-latest-record-with-filter-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!