10

In Django REST Framework, when you query a database model and it does not exist an exception will be raised as ModelName.DoesNotExist.

This exception will change according to the model name.

For example:

  • Querying the Car model will raise Car.DoesNotExist
  • Querying the Plane model will raise Plane.DoesNotExist

This causes trouble, since you can not catch the exception at one common place, because you do not know the parent class of the Exception.

You have to catch a different exception every time you query a different model, for example:

try:
    return Car.objects.get(pk=1)
except Car.DoesNotExist:
    raise Http404

Why was this feature designed like this?

Is it possible to capture a common exception?

Steffo
  • 305
  • 5
  • 13
Kramer Li
  • 2,284
  • 5
  • 27
  • 55

1 Answers1

13

You can use ObjectDoesNotExist:

from django.core.exceptions import ObjectDoesNotExist

try:
    return Car.objects.get(pk=1)
except ObjectDoesNotExist:
    raise Http404

ObjectDoesNotExist will catch DoesNotExist exceptions for all models.

Django also provides get_object_or_404() shortcut so you dont need to raise Http404 explicitly.

neverwalkaloner
  • 46,181
  • 7
  • 92
  • 100
  • Thanks but why django provided a detailed Exception when it already have the ObjectDoesNotExist – Kramer Li Sep 30 '18 at 07:19
  • @KramerLi 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. – neverwalkaloner Sep 30 '18 at 07:21
  • @KramerLi from this part of the docs: https://docs.djangoproject.com/en/2.1/ref/models/instances/#doesnotexist – neverwalkaloner Sep 30 '18 at 07:21