Catching DoesNotExist exception in a custom manager in Django

PythonDjangoExceptionDjango Custom-Manager

Python Problem Overview


I have a custom manager for a Django model. I don't seem to be able to catch DoesNotExist exception here. I know how to do it inside the model but it didn't work here:

class TaskManager(models.Manager):
    def task_depend_tree(self, *args, **kwargs):
        if "id" in kwargs:
            try:
                task = self.get(id=kwargs["id"])
            except DoesNotExist:
                raise Http404

Get_object_or_404 doesn't work either. What is wrong here?

Python Solutions


Solution 1 - Python

Try either using ObjectDoesNotExist instead of DoesNotExist or possibly self.DoesNotExist. If all else fails, just try and catch a vanilla Exception and evaluate it to see it's type().

from django.core.exceptions import ObjectDoesNotExist

Solution 2 - Python

As panchicore suggested, self.model is the way to go.

class TaskManager(models.Manager):
    def task_depend_tree(self, *args, **kwargs):
        if "id" in kwargs:
            try:
                task = self.get(id=kwargs["id"])
            except self.model.DoesNotExist:
                raise Http404

Solution 3 - Python

If you need to implement this on a list method (DRF) using GenericViewSet, and need an empty list to be returned, use this:

    def list(self, request, *args, **kwargs):
    self.get_object() # I use this to trigger the object_permission
    try:
        queryset = self.queryset.filter(user=(YourModel.objects.get(user=request.user).user))
    except YourModel.DoesNotExist:
        return Response(YourModel.objects.none())

    serializer = YSourModelSerializer(queryset, many=True)
    return Response(serializer.data)

Solution 4 - Python

you can use the DoesNotExist from the Manager.model (self.model) instance, when you say objects = MyManager() you are assigning self.model inside MyManager class.

        try:
            task = self.get(id=kwargs["id"])
            return task
        except self.DoesNotExist:
            return None

Solution 5 - Python

In Django, every object from model has an exception property DoesNotExists. So you can call it from the object itself or from the exceptions module.

From object (self):

from django.db import models

class TaskManager(models.Manager):
    def task_depend_tree(self, *args, **kwargs):
        if "id" in kwargs:
            try:
                task = self.get(id=kwargs["id"])
            except self.model.DoesNotExist:
                raise Http404

From exceptions module:

from django.core.exceptions import ObjectDoesNotExist

try:
    return "Calling object"
except ObjectDoesNotExist:
    raise Http404

Solution 6 - Python

I handle the exception this way and it worked.

from django.core.exceptions import ObjectDoesNotExist

try:
    task = self.get(id=kwargs["id"])
except ObjectDoesNotExist as DoesNotExist:
    raise Http404

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSepermanView Question on Stackoverflow
Solution 1 - PythonJeff TriplettView Answer on Stackoverflow
Solution 2 - PythondanbalView Answer on Stackoverflow
Solution 3 - PythonThéo T. CarranzaView Answer on Stackoverflow
Solution 4 - PythonpanchicoreView Answer on Stackoverflow
Solution 5 - PythonKurt BrownView Answer on Stackoverflow
Solution 6 - PythonSanti RodriguezView Answer on Stackoverflow