2

The template has no "DoesNotExists" attribute in the manager

 2 years ago
source link: https://www.codesd.com/item/the-template-has-no-doesnotexists-attribute-in-the-manager.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

The template has no "DoesNotExists" attribute in the manager

advertisements

Django 1.7 Exceptions documentation exceptions.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.

Based on above documentation I wrote custom Model Manager:

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)

Note that: lines with {'country': settings.ACTIVE_COUNTRY} and with{'country': settings.DEFAULT_COUNTRY} are simplified for this example

class CountryModelMixing(models.Model):
    country = models.CharField(
        max_length=2,
        default=settings.DEFAULT_COUNTRY,
        choices=settings.COUNTRIES,
        verbose_name=_('country')
    )

    objects = CountryManager()

    class Meta:
        abstract=True

class Product(CountryModelMixing):
    name = models.CharField(max_length=40)

and in code when I'm trying to:

Product.objects.get_special(name='abc')

And I'm getting following error:

/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 does not take an "s":

except self.model.DoesNotExist:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK