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
DoesNotExistexception 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.