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 not
found. For example, QuerySet.get() will raise it when no object
is found for the given lookups.

Django provides a DoesNotExist exception as an attribute of
each model class to identify the class of object that could not be
found, 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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)