How do you catch this exception?

前端 未结 6 1418
孤独总比滥情好
孤独总比滥情好 2020-12-23 15:28

This code is in django/db/models/fields.py It creates/defines an exception?

class ReverseSingleRelatedObjectDescriptor(six.with_metaclass(RenameRelatedObjec         


        
6条回答
  •  Happy的楠姐
    2020-12-23 16:17

    If your related model is called Foo you can just do:

    except Foo.DoesNotExist:
    

    Django is amazing when its 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:

    ObjectDoesNotExist and DoesNotExist

    exception DoesNotExist

    The DoesNotExist exception is raised when an object is not found for the given parameters of a query. Django provides a DoesNotExist exception as an attribute of each model class to identify the class of object that could not be found and to allow you to catch a particular model class with try/except.

    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.

提交回复
热议问题