Django:测试获取查询
好吧,我厌倦了写这个......
res = Something.objects.filter(asdf=something)
if res:
single = res[0]
else:
single = None
if single:
# do some stuff
我更愿意能够做这样的事情:
single = Something.objects.filter(asdf=something)
if single:
#do some stuff
我希望能够在不测试过滤结果的情况下抓取一个单个对象。
换句话说,当我知道将有 1 个或 0 个匹配条目时,我想直接跳到该条目,否则只会得到“无”。当尝试将这些查询压缩到一行中时,与 .get 一起出现的DoesNotExist 错误并不总是那么有效。
有什么办法可以做到我所描述的吗?
Okay, so I am sick of writing this...
res = Something.objects.filter(asdf=something)
if res:
single = res[0]
else:
single = None
if single:
# do some stuff
I would much rather be able to do something like this:
single = Something.objects.filter(asdf=something)
if single:
#do some stuff
I want to be able to grab a single object without testing the filtered results.
In other words, when i know there is either going to be 1 or 0 matching entries, I would like to jump right to that entry, otherwise just get a 'None'. The DoesNotExist error that goes along with .get does not always work so well when trying to compress these queries into a single line.
Is there any way to do what I have described?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
django-annoying 项目包含一个
get_object_or_None
快捷方式来执行此操作,尽管自己写起来很简单。The django-annoying project includes a
get_object_or_None
shortcut which does this, although it's trivial to write it yourself.创建自定义
管理器
它将您厌倦重复的部分封装为一种方法(具有比下面的更好的名称),或者只编写一个实用程序函数,它可以在不影响模型定义的情况下执行相同的操作:用法:
Create a custom
Manager
which encapsulates the bit you're sick of repeating as a method (with a better name than the one below) or just write a utility function which does the same without the hit to model definitions:Usage: