How do you catch this exception?
If your related model is called Foo you can just do:
except Foo.DoesNotExist:
Django is amazing when it's not terrifying. RelatedObjectDoesNotExist
is a property that returns a type that is figured out dynamically at runtime. That type uses self.field.rel.to.DoesNotExist
as a base class.
According to Django documentation:
DoesNotExist
exception Model.DoesNotExist
This exception is raised by the ORM when an expected object is notfound. For example,
QuerySet.get()
will raise it when no objectis found for the given lookups.Django provides a
DoesNotExist
exception as an attribute ofeach model class to identify the class of object that could not befound, allowing you to catch exceptions for a particular model class.The exception is a subclass of
django.core.exceptions.ObjectDoesNotExist
.
This is the magic that makes that happen. Once the model has been built up, self.field.rel.to.DoesNotExist
is the does-not-exist exception for that model.