Catching DoesNotExist exception in a custom manager in Django

61,707

Solution 1

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

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

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

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

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
Share:
61,707

Related videos on Youtube

Seperman
Author by

Seperman

Currently focusing on writing search engines for e-Commerce. Zepworks Linked in Github

Updated on July 05, 2022

Comments

  • Seperman
    Seperman almost 2 years

    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?

    • Daniel Roseman
      Daniel Roseman over 11 years
      What does "doesn't work" mean, for both those cases? What actually happens?
    • Seperman
      Seperman over 11 years
      @DanielRoseman NameError: global name 'DoesNotExist' is not defined
  • Seperman
    Seperman over 11 years
    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.
  • Philipp Zedler
    Philipp Zedler over 11 years
    self.DoesNotExist will obviously not help, because self exists if it has such a method. Use instead task.DoesNotExist or ObjectDoesNotExist.
  • Jeff Triplett
    Jeff Triplett over 11 years
    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.
  • Seperman
    Seperman over 11 years
    I had to import ObjectDoesNotExist and it worked to catch DoesNotExist: from django.db.models.base import ObjectDoesNotExist Thanks!
  • Sudhakaran Packianathan
    Sudhakaran Packianathan almost 7 years
    This will not work. You have to use self.model.DoesNotExist
  • Robert Killkelley
    Robert Killkelley over 3 years
    This is the cleanest way of handling this exception since it does not involve importing the Exception
  • Pranav Kumar
    Pranav Kumar over 2 years
    The name DoesNotExist is quite misleading here and not used at all