[Django]-Django: More helpful error messages for DoesNotExist errors?

3👍

As @Jeeyoung proved, it’s impossible to introspect on DoesNotExist errors to get the arguments used… So I’ve written a small function which monkey patches objects.get, catching DoesNotExists and adding the query to the error:

>>> class MyModel(m.Model):
...     pass
...
>>> patch_objects_get(MyModel)
>>> MyModel.objects.get(id=3141)
Traceback (most recent call last):
...
DoesNotExist: MyModel matching {"id": 42} does not exist
>>>

The code is at https://gist.github.com/702513

2👍

👤JAL

1👍

I was looking at the code for get(), and found the following

raise self.model.DoesNotExist("%s matching query does not exist."
    % self.model._meta.object_name)
raise self.model.MultipleObjectsReturned("get() returned more than one %s -- it returned %s! Lookup parameters were %s"
    % (self.model._meta.object_name, num, kwargs))

So I guess there’s no good way to introspect the exception.

You can either do what Felix Kling has suggested (write a wrapper method) around get(). You can even make it more generic by doing something like:

def my_get(*args, **kwargs):
    try:
        Foo.object.get(*args, **kwargs)
    except Foo.DoesNotExist:
        print "No object matching conditions (*%s, **%s) found." % (args, kwargs)

0👍

Don’t monkey-patch, override:

from django.db import models
from django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist


class ElJefe(models.Manager):
    """A custom manager."""

    def get(self, *args, **kwargs):
        """Make the standard .get() error message useful."""
        try:
            return super().get(*args, **kwargs)
        except (ObjectDoesNotExist, MultipleObjectsReturned) as err:
            msg = f'\n    query was: {args}, {kwargs}'
            err.args = (err.args[0] + msg,)  # well…
            raise err


class BaseModel(models.Model):
    """Common fields defined here."""

    objects = ElJefe()

    # ...

Leave a comment