Python 在 Django 中使用过滤器获取最新记录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15675672/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get the latest record with filter in Django
提问by doniyor
I am trying to get the latest Django model object but cannot seem to succeed.
我正在尝试获取最新的 Django 模型对象,但似乎无法成功。
Neither of these are working:
这些都不起作用:
obj = Model.objects.filter(testfield=12).latest()
obj = Model.objects.latest().filter(testfield=12)
采纳答案by catherine
obj= Model.objects.filter(testfield=12).order_by('-id')[0]
回答by acjay
latestis 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_bymeta attribute, as mentioned here.
latest真正设计用于处理日期字段(它可能也适用于其他全序类型,但不确定)。你可以使用它没有指定字段名的唯一方法是通过设置get_latest_by元属性,提到这里。
回答by acjay
See the docs from django: https://docs.djangoproject.com/en/dev/ref/models/querysets/#latest
查看 django 的文档:https: //docs.djangoproject.com/en/dev/ref/models/querysets/#latest
You need to specify a field in latest(). eg.
您需要在 latest() 中指定一个字段。例如。
obj= Model.objects.filter(testfield=12).latest('testfield')
Or if your model's Meta specifies get_latest_by, you can leave off the field_nameargument to earliest() or latest(). Django will use the field specified in get_latest_byby default.
或者,如果你的模型的元指定get_latest_by,可以去掉的field_name参数earliest() or latest()。Django 将get_latest_by默认使用 中指定的字段。
回答by Thomas John
obj= Model.objects.filter(testfield=12).order_by('-id')[:1]is the right solution
obj= Model.objects.filter(testfield=12).order_by('-id')[:1]是正确的解决方案

