Where do I import the `DoesNotExist` exception in Django 1.10 from? Where do I import the `DoesNotExist` exception in Django 1.10 from? django django

Where do I import the `DoesNotExist` exception in Django 1.10 from?


The exception is called ObjectDoesNotExists [Django-doc] in case the model is not known, so you import it as:

from django.core.exceptions import ObjectDoesNotExist

The Object is used to avoid confusion with the DoesNotExist exception every model has (you can see Object as a "generalization" of objects of all models).

Note however that if you know what the model is of the model that you query for, it is better to use a more restricted exception, like:

try:    SomeModel.objects.get(pk=14)except SomeModel.DoesNotExist:    # ... do something    pass

Like specified in the documentation of the model attributes [Django-doc]:

Django provides a DoesNotExist exception as an attribute of each model class to identify the class of object that could not be found and to allow you to catch a particular model class with try/except. The exception is a subclass of django.core.exceptions.ObjectDoesNotExist.

Such that you do not - by accident - catch exceptions because some (related) model can not be fetched. Typically the span of a try-except block should be as small as possible, and the exception as "explicit" as possible.


It should be ObjectDoesNotExist:

from django.core.exceptions import ObjectDoesNotExist

You can also catch exception for specific model like this:

from .your_models import ModelClassModelClass.DoesNotExist