如果对象存在,我如何获取它;如果对象不存在,我如何获取它?

2024-06-28 20:35:50 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我怎么能让go变成None而不是DoesNotExist


Tags: 对象name模型nonego管理器getobjects
3条回答

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

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

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

From django docs

get() raises a DoesNotExist exception if an object is not found for the given parameters. This exception is also an attribute of the model class. The DoesNotExist exception inherits from django.core.exceptions.ObjectDoesNotExist

您可以捕获异常并将None分配给go。

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

由于django 1.6,您可以使用first()方法,如下所示:

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

相关问题 更多 >