How do you catch this exception?

前端 未结 6 1420
孤独总比滥情好
孤独总比滥情好 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条回答
  •  再見小時候
    2020-12-23 16:26

    The RelatedObjectDoesNotExist exception is created dynamically at runtime. Here is the relevant code snippet for the ForwardManyToOneDescriptor and ReverseOneToOneDescriptor descriptors:

    @cached_property
    def RelatedObjectDoesNotExist(self):
        # The exception can't be created at initialization time since the
        # related model might not be resolved yet; `self.field.model` might
        # still be a string model reference.
        return type(
            'RelatedObjectDoesNotExist',
            (self.field.remote_field.model.DoesNotExist, AttributeError),
            {}
        )
    

    So the exception inherits from .DoesNotExist and AttributeError. In fact, the complete MRO for this exception type is:

    [, 
    .DoesNotExist'>,
    ,
    ,
    ,
    ,
    ]
    

    The basic takeaway is you can catch .DoesNotExist, ObjectDoesNotExist (import from django.core.exceptions) or AttributeError, whatever makes the most sense in your context.

提交回复
热议问题