Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
87 views
in Technique[技术] by (71.8m points)

Django: Where does "DoesNotExist" come from?

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.

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

question from:https://stackoverflow.com/questions/2143506/django-where-does-doesnotexist-come-from

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

DoesNotExist is documented here:

The DoesNotExist exception inherits from django.core.exceptions.ObjectDoesNotExist, so you can target multiple DoesNotExist exceptions.

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.

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,), {}))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...