I'm having trouble figuring this out. I'm trying to catch an exception in the case of a specific object not existing, but the line
from django.core.exceptions import DoesNotExist
gives me the cannot find reference in exeptions.py
warning. If the exception is not specified in that file, where do I find it?
The DoesNotExist exception is raised when an object is not found for the given parameters of a query. 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 NoReverseMatch exception is raised by django.
1) Django Exception classes – It occurs when the Django models are loaded before the Django app itself. – This exception occurs when you are writing your own scripts and not with default Django app files. 2. ObjectDoesNotExist. As the name suggests, occurs when Object does not exist.
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 ofdjango.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With