Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 507
SeSodesa Avatar asked Sep 22 '18 10:09

SeSodesa


People also ask

How do you handle does not exist in Django?

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 .

What is the name of the Django exception raised when trying to insert a record with a wrong date format?

The NoReverseMatch exception is raised by django.

What is Django exception explain with an example?

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.


1 Answers

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.

like image 64
Willem Van Onsem Avatar answered Sep 27 '22 22:09

Willem Van Onsem