Django:测试获取查询

发布于 2024-08-27 02:22:08 字数 477 浏览 5 评论 0原文

好吧,我厌倦了写这个......

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

塔塔猫 2024-09-03 02:22:08

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.

萤火眠眠 2024-09-03 02:22:08

创建自定义管理器它将您厌倦重复的部分封装为一种方法(具有比下面的更好的名称),或者只编写一个实用程序函数,它可以在不影响模型定义的情况下执行相同的操作:

class MyManager(models.Manager):
    def get_or_none(self, **kwargs):
        try:
            return self.get(**kwargs)
        except self.model.DoesNotExist:
            return None

class MyModel(models.Model):
    objects = MyManager()

用法:

MyModel.objects.get_or_none(asdf=something)

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:

class MyManager(models.Manager):
    def get_or_none(self, **kwargs):
        try:
            return self.get(**kwargs)
        except self.model.DoesNotExist:
            return None

class MyModel(models.Model):
    objects = MyManager()

Usage:

MyModel.objects.get_or_none(asdf=something)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文