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👍
Sure, you can get the SQL that Django has executed.
See http://docs.djangoproject.com/en/dev/faq/models/#how-can-i-see-the-raw-sql-queries-django-is-running
👤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)
- [Django]-Django migrations : relation already exists
- [Django]-Django : saving form to database
- [Django]-Django-Rest-Framework: Can I create a viewset with two different methods with the same url_path, but different request methods?
- [Django]-Python / Django – Exception Value: 'WSGIRequest' object has no attribute 'Meta'
- [Django]-Django: Add additional fields to UserCreationForm
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()
# ...
- [Django]-IF statement not working with list difference
- [Django]-Django: can't bind an uploaded image to a form ImageField()
Source:stackexchange.com