84

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?

tshepang
  • 12,111
  • 21
  • 91
  • 136
Seperman
  • 4,254
  • 1
  • 28
  • 27

6 Answers6

146

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

Jeff Triplett
  • 2,216
  • 1
  • 16
  • 8
  • I had tried Self.DoesNotExist and it failed. The error I get when something doesn't exist in database is: `NameError: global name 'DoesNotExist' is not defined` So I need to import DoesNotExist from somewhere. I assumed it is in models.Model but models.Model.DoesNotExist didn't work. – Seperman Jan 10 '13 at 18:43
  • self.DoesNotExist will obviously not help, because self exists if it has such a method. Use instead `task.DoesNotExist` or `ObjectDoesNotExist`. – Philipp Zedler Jan 11 '13 at 09:02
  • Did you try my suggestion of `ObjectDoesNotExist`? The other syntax might be self.model.DoesNotExist... but I'm not sure off the top of my head. – Jeff Triplett Jan 11 '13 at 17:10
  • 13
    I had to import ObjectDoesNotExist and it worked to catch DoesNotExist: `from django.db.models.base import ObjectDoesNotExist ` Thanks! – Seperman Jan 17 '13 at 07:23
18

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
danbal
  • 1,481
  • 3
  • 14
  • 19
6

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)
Théo T. Carranza
  • 7,813
  • 1
  • 21
  • 14
2

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
panchicore
  • 11,451
  • 12
  • 74
  • 100
1

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
Kurt Brown
  • 39
  • 1
  • 4
0

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

Santi Rodriguez
  • 164
  • 1
  • 9