Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Where does "DoesNotExist" come from?

All the time in Django I see DoesNotExist being raised like in db.models.fields.related.py. Not ObjectDoesNotExist which is defined in django.core.exceptions, but just DoesNotExist. Where is this exception class defined, or am I not fully understanding exceptions? I've checked that it's not in exceptions (at least not that I know of). I'm confused obviously.

Note: It also comes free, as an attribute of a model sub-class instance, like `self.someforeignkey.DoesNotExist. How is this possible?

like image 611
orokusaki Avatar asked Jan 26 '10 23:01

orokusaki


People also ask

How do I get Donotexist in Django?

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().

What is OuterRef Django?

to Django users. According to the documentation on models. OuterRef: It acts like an F expression except that the check to see if it refers to a valid field isn't made until the outer queryset is resolved.

What is Integrityerror in Django?

This means that your DB is expecting that field to have a value. So when it doesn't you get an error. null. If True, Django will store empty values as NULL in the database. Default is False.


1 Answers

DoesNotExist is documented here:

The DoesNotExist exception inherits from django.core.exceptions.ObjectDoesNotExist, so you can target multiple DoesNotExist exceptions.

so you can perfectly well use except ObjectDoesNotExist: and catch all the model-specific DoesNotExist exceptions that might be raised in the try clause, or use except SomeSpecificModel.DoesNotExist: when you want to be more specific.

If you're looking for the specific spot in Django's source code where this attribute is added to model classes, see here, lines 34-37:

# Create the class. new_class = type.__new__(cls, name, bases, {'__module__': attrs.pop('__module__')}) new_class.add_to_class('_meta', Options(attrs.pop('Meta', None))) new_class.add_to_class('DoesNotExist', types.ClassType('DoesNotExist', (ObjectDoesNotExist,), {})) 
like image 178
Alex Martelli Avatar answered Sep 28 '22 18:09

Alex Martelli