#sample code
try:
Model_1.objects.get(id=1)
Model_2.objects.get(id=1)
Model_3.objects.get(id=1)
Model_4.objects.get(id=1)
except (Model_1.DoesNotExist, Model_2.DoesNotExist, Model_3.DoesNotExist, Model_4.DoesNotExist):
... # do something
我不确定这是否是捕获 N
模型异常的正确方法。还有其他方法可以代替 DoesNotExist
例外吗?
答案 0 :(得分:7)
您可以使用ObjectDoesNotExist
从Django文档中,
DoesNotExist
异常的基类;try/except
的ObjectDoesNotExist
将捕获所有模型的DoesNotExist
例外 。
因此,请尝试以下操作
from django.core.exceptions import ObjectDoesNotExist
try:
Model_1.objects.get(id=1)
Model_2.objects.get(id=1)
Model_3.objects.get(id=1)
Model_4.objects.get(id=1)
except ObjectDoesNotExist:
... # do something