Django: More helpful error messages for DoesNotExist errors?


Is it possible to coax Django into giving more information for DoesNotExist errors?

For example, it would be really nice if they would include the query… Something like:

>>> Foo.objects.get(id="example_id")
DoesNotExist: No objects matching id="example_id" found


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

Answered By – David Wolever

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published