type object ‘MyModel’ has no attribute ‘DoesNotExist’

3 May 2023

Saw a surprising error the other day in Sentry: AttributeError: type object 'MyModel' has no attribute 'DoesNotExist'. I’d never seen this before, so I went to take a look at the definition of MyModel, and way down past all of the field declarations I saw the following:

class MyModel(models.Model):
    ...

    class Meta:
        abstract = True

A quick check of the relevant section of the Django models code revealed that the DoesNotExist exception is one of a number of attributes added dynamically to each new model class, but not for abstract models, which makes sense. The same goes for the MultipleObjectsReturned exception, too.