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每次都会提出DoesNotExist异常。 在python中处理此问题的惯用方法是用try-catch将其包装起来:
我所做的,是将models.Manager子类化,创建一个类似于上面代码的
safe_get
,并将该管理器用于我的模型。这样你就可以写:SomeModel.objects.safe_get(foo='bar')
。From django docs
您可以捕获异常并将
None
分配给go。由于django 1.6,您可以使用first()方法,如下所示:
相关问题 更多 >
编程相关推荐