Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture the Model.DoesNotExist exception in Django rest framework?

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?

like image 468
Kramer Li Avatar asked Sep 30 '18 07:09

Kramer Li


People also ask

How do I return an error response in Django?

I want to return a HTTP 400 response from my django view function if the request GET data is invalid and cannot be parsed. Return a HttpResponseBadRequest : docs.djangoproject.com/en/dev/ref/request-response/… You can create an Exception subclass like Http404 to have your own Http400 exception.

How do you increase validation error in DRF?

The easiest way to change the error style through all the view in your application is to always use serializer. is_valid(raise_exception=True) , and then implement a custom exception handler that defines how the error response is created.


1 Answers

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.

like image 148
neverwalkaloner Avatar answered Sep 23 '22 15:09

neverwalkaloner