How do you catch this exception? How do you catch this exception? django django

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.


If you don't want to import the related model class, you can:

except MyModel.related_field.RelatedObjectDoesNotExist:

or

except my_model_instance._meta.model.related_field.RelatedObjectDoesNotExist:

where related_field is the field name.


To catch this exception in general, you can do

from django.core.exceptions import ObjectDoesNotExisttry:    # Your code hereexcept ObjectDoesNotExist:    # Handle exception