关于python:Model在Manager中没有属性“DoesNotExists”

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)

注:以{'country': settings.ACTIVE_COUNTRY}和WIT{'country': settings.DEFAULT_COUNTRY}为例,简化了Lines with {'country': settings.ACTIVE_COUNTRY}and WIT{'country': settings.DEFAULT_COUNTRY}

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'


DoesNotExist不取"s":

1
except self.model.DoesNotExist:

您拼错了异常的名称:

1
2
except self.model.DoesNotExists:
#                             ^

例外名称是DoesNotExist,末尾没有s