Catching DoesNotExist exception in a custom manager in Django

Seperman picture Seperman · Jan 10, 2013 · Viewed 60.6k times · Source

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?

Answer

Jeff Triplett picture Jeff Triplett · Jan 10, 2013

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