Model has no attribute 'DoesNotExists' in Manager
Django 1.7 Exceptions documentation exceptions.
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.
基于上面的文献,我创建了自定义模型经理:
1 2 3 4 5 6 7 8 9 | class CountryManager(models.Manager): def get_special(self, *args, **kwargs): kwargs.update({'country': settings.ACTIVE_COUNTRY}) try: return self.get(*args, **kwargs) except self.model.DoesNotExists: self.logger.warning('Unable to find specific object using filter {}'.format(kwargs)) kwargs.update({'country': settings.DEFAULT_COUNTRY}) return self.get(*args, **kwargs) |
注:以
ZZU1
当我试着
1 | Product.objects.get_special(name='abc') |
我会跟踪错误
1 2 3 4 5 6 | /opt/src/common/managers.py in get_special(self, *args, **kwargs) 40 try: 41 return self.get(*args, **kwargs) ---> 42 except self.model.DoesNotExists: 43 self.logger.warning('Unable to find specific object using filter {}'.format(kwargs)) AttributeError: type object 'Product' has no attribute 'DoesNotExists' |
1 | except self.model.DoesNotExist: |
您拼错了异常的名称:
1 2 | except self.model.DoesNotExists: # ^ |
例外名称是