本文介绍了如何获得该对象(如果存在)或“无”(如果不存在)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我请求模型管理器获取对象时,如果没有匹配的对象,它将引发 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每次都会引发DidNotExist异常。
在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

我要做的是继承模型。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').

这篇关于如何获得该对象(如果存在)或“无”(如果不存在)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 07:19