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

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

而不是DoesNotExist,我怎么能去是None代替?


当前回答

来自django docs

如果没有找到给定参数的对象,get()将引发一个DoesNotExist异常。这个异常也是模型类的一个属性。DoesNotExist异常继承自django.core.exceptions.ObjectDoesNotExist

您可以捕获异常并将None指定为go。

from django.core.exceptions import ObjectDoesNotExist
try:
    go  = Content.objects.get(name="baby")
except ObjectDoesNotExist:
    go = None

其他回答

如果发生这样的事呢?

go = (Content.objects.filter(name="value") or [None])[0]

从django 1.6开始,你可以像这样使用first()方法:

Content.objects.filter(name="baby").first()

你可以在过滤器中使用exists:

Content.objects.filter(name="baby").exists()
#returns False or True depending on if there is anything in the QS

如果你只想知道它是否存在,这是另一种选择

没有“内置”的方法可以做到这一点。Django每次都会抛出DoesNotExist异常。 在python中,处理这个问题的惯用方法是将其封装在try catch中:

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

我所做的就是将模型子类化。Manager,创建一个类似于上面代码的safe_get,并将该Manager用于我的模型。这样你就可以写:sommodel .objects.safe_get(foo='bar')。

没有例外:

if SomeModel.objects.filter(foo='bar').exists():
    x = SomeModel.objects.get(foo='bar')
else:
    x = None

使用异常:

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

关于在python中什么时候应该使用异常有一点争论。一方面,“请求原谅比请求允许容易”。虽然我同意这一点,但我认为应该保留一个异常,好吧,异常,并且“理想情况”应该运行而不碰到异常。