How do you catch this exception?

前端 未结 6 1397
孤独总比滥情好
孤独总比滥情好 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:01

    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.

    0 讨论(0)
  • 2020-12-23 16:07

    To catch this exception in general, you can do

    from django.core.exceptions import ObjectDoesNotExist
    
    try:
        # Your code here
    except ObjectDoesNotExist:
        # Handle exception
    
    0 讨论(0)
  • 2020-12-23 16:09

    Little bit late but helpful for others.

    2 ways to handle this.

    1st :

    When we need to catch exception

    >>> from django.core.exceptions import ObjectDoesNotExist
    >>> try:
    >>>     p2.restaurant
    >>> except ObjectDoesNotExist:
    >>>     print("There is no restaurant here.")
    There is no restaurant here.
    

    2nd: When don't want to handle exception

    >>> hasattr(p2, 'restaurant')
    False
    
    0 讨论(0)
  • 2020-12-23 16:15

    tdelaney's answer is great for regular code paths, but if you need to know how to catch this exception in tests:

    from django.core.exceptions import ObjectDoesNotExist
    
    ...
    
        def testCompanyRequired(self):
            with self.assertRaises(ObjectDoesNotExist):
                employee = Employee.objects.create()
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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 <model name>.DoesNotExist and AttributeError. In fact, the complete MRO for this exception type is:

    [<class 'django.db.models.fields.related_descriptors.RelatedObjectDoesNotExist'>, 
    <class '<model module path>.DoesNotExist'>,
    <class 'django.core.exceptions.ObjectDoesNotExist'>,
    <class 'AttributeError'>,
    <class 'Exception'>,
    <class 'BaseException'>,
    <class 'object'>]
    

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

    0 讨论(0)
提交回复
热议问题