如果对象存在,我如何获取该对象,如果它在 Django 中不存在,我如何获取它? [英] How do I get the object if it exists, or None if it does not exist in Django?

查看:25
本文介绍了如果对象存在,我如何获取该对象,如果它在 Django 中不存在,我如何获取它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我要求模型管理器获取一个对象时,它会在没有匹配对象时引发 DoesNotExist.

When I ask the model manager to get an object, it raises DoesNotExist when there is no matching object.

go = Content.objects.get(name="baby")

代替 DoesNotExist,我怎样才能让 go 变成 None 呢?

Instead of DoesNotExist, how can I have go be None instead?

推荐答案

没有内置"的方式来做到这一点.Django 每次都会引发DoesNotExist 异常.在 python 中处理这个的惯用方法是将它包装在一个 try catch 中:

There is no 'built in' way to do this. Django will raise the DoesNotExist exception every time. The idiomatic way to handle this in python is to wrap it in a try catch:

try:
    go = SomeModel.objects.get(foo='bar')
except SomeModel.DoesNotExist:
    go = None

我所做的是将models.Manager子类化,像上面的代码一样创建一个safe_get,然后将那个管理器用于我的模型.这样你就可以写:SomeModel.objects.safe_get(foo='bar').

What I did do, is to subclass models.Manager, create a safe_get like the code above and use that manager for my models. That way you can write: SomeModel.objects.safe_get(foo='bar').

这篇关于如果对象存在,我如何获取该对象,如果它在 Django 中不存在,我如何获取它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆