本文介绍了Django:“ DoesNotExist”在哪里?来自?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Django中,所有时间我都看到 DoesNotExist db.models.fields.related.py 一样被提出。不是 django.core.exceptions 中定义的 ObjectDoesNotExist ,而只是 DoesNotExist 。该异常类在哪里定义,或者我没有完全理解异常?我已经检查了它是否有异常(至少不是我所知道的)。我显然很困惑。

All the time in Django I see DoesNotExist being raised like in db.models.fields.related.py. Not ObjectDoesNotExist which is defined in django.core.exceptions, but just DoesNotExist. Where is this exception class defined, or am I not fully understanding exceptions? I've checked that it's not in exceptions (at least not that I know of). I'm confused obviously.

注意:它也是免费的,作为模型子类实例的属性,例如self.someforeignkey.DoesNotExist。

Note: It also comes free, as an attribute of a model sub-class instance, like `self.someforeignkey.DoesNotExist. How is this possible?

推荐答案

DoesNotExist 已记录为:

因此您可以很好地使用,除了ObjectDoesNotExist:并捕获在 try 子句中可能引发的所有特定于模型的 DoesNotExist 异常,或使用除了SomeSpecificModel.DoesNotExist:,当您想更具体时。

so you can perfectly well use except ObjectDoesNotExist: and catch all the model-specific DoesNotExist exceptions that might be raised in the try clause, or use except SomeSpecificModel.DoesNotExist: when you want to be more specific.

如果您正在Django的源代码中寻找特定位置将该属性添加到模型类的位置,请参见,第34-37行:

If you're looking for the specific spot in Django's source code where this attribute is added to model classes, see here, lines 34-37:

# Create the class.
new_class = type.__new__(cls, name, bases, {'__module__': attrs.pop('__module__')})
new_class.add_to_class('_meta', Options(attrs.pop('Meta', None)))
new_class.add_to_class('DoesNotExist', types.ClassType('DoesNotExist', (ObjectDoesNotExist,), {}))

这篇关于Django:“ DoesNotExist”在哪里?来自?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-11 10:55