PageRenderTime 55ms CodeModel.GetById 43ms app.highlight 9ms RepoModel.GetById 1ms app.codeStats 0ms

/django/contrib/contenttypes/models.py

https://code.google.com/p/mango-py/
Python | 105 lines | 77 code | 5 blank | 23 comment | 2 complexity | b243fe80ace979be062dd1d81c892784 MD5 | raw file
  1from django.db import models
  2from django.utils.translation import ugettext_lazy as _
  3from django.utils.encoding import smart_unicode
  4
  5class ContentTypeManager(models.Manager):
  6
  7    # Cache to avoid re-looking up ContentType objects all over the place.
  8    # This cache is shared by all the get_for_* methods.
  9    _cache = {}
 10
 11    def get_by_natural_key(self, app_label, model):
 12        try:
 13            ct = self.__class__._cache[self.db][(app_label, model)]
 14        except KeyError:
 15            ct = self.get(app_label=app_label, model=model)
 16        return ct
 17
 18    def get_for_model(self, model):
 19        """
 20        Returns the ContentType object for a given model, creating the
 21        ContentType if necessary. Lookups are cached so that subsequent lookups
 22        for the same model don't hit the database.
 23        """
 24        opts = model._meta
 25        while opts.proxy:
 26            model = opts.proxy_for_model
 27            opts = model._meta
 28        key = (opts.app_label, opts.object_name.lower())
 29        try:
 30            ct = self.__class__._cache[self.db][key]
 31        except KeyError:
 32            # Load or create the ContentType entry. The smart_unicode() is
 33            # needed around opts.verbose_name_raw because name_raw might be a
 34            # django.utils.functional.__proxy__ object.
 35            ct, created = self.get_or_create(
 36                app_label = opts.app_label,
 37                model = opts.object_name.lower(),
 38                defaults = {'name': smart_unicode(opts.verbose_name_raw)},
 39            )
 40            self._add_to_cache(self.db, ct)
 41
 42        return ct
 43
 44    def get_for_id(self, id):
 45        """
 46        Lookup a ContentType by ID. Uses the same shared cache as get_for_model
 47        (though ContentTypes are obviously not created on-the-fly by get_by_id).
 48        """
 49        try:
 50            ct = self.__class__._cache[self.db][id]
 51        except KeyError:
 52            # This could raise a DoesNotExist; that's correct behavior and will
 53            # make sure that only correct ctypes get stored in the cache dict.
 54            ct = self.get(pk=id)
 55            self._add_to_cache(self.db, ct)
 56        return ct
 57
 58    def clear_cache(self):
 59        """
 60        Clear out the content-type cache. This needs to happen during database
 61        flushes to prevent caching of "stale" content type IDs (see
 62        django.contrib.contenttypes.management.update_contenttypes for where
 63        this gets called).
 64        """
 65        self.__class__._cache.clear()
 66
 67    def _add_to_cache(self, using, ct):
 68        """Insert a ContentType into the cache."""
 69        model = ct.model_class()
 70        key = (model._meta.app_label, model._meta.object_name.lower())
 71        self.__class__._cache.setdefault(using, {})[key] = ct
 72        self.__class__._cache.setdefault(using, {})[ct.id] = ct
 73
 74class ContentType(models.Model):
 75    name = models.CharField(max_length=100)
 76    app_label = models.CharField(max_length=100)
 77    model = models.CharField(_('python model class name'), max_length=100)
 78    objects = ContentTypeManager()
 79
 80    class Meta:
 81        verbose_name = _('content type')
 82        verbose_name_plural = _('content types')
 83        db_table = 'django_content_type'
 84        ordering = ('name',)
 85        unique_together = (('app_label', 'model'),)
 86
 87    def __unicode__(self):
 88        return self.name
 89
 90    def model_class(self):
 91        "Returns the Python model class for this type of content."
 92        from django.db import models
 93        return models.get_model(self.app_label, self.model)
 94
 95    def get_object_for_this_type(self, **kwargs):
 96        """
 97        Returns an object of this type for the keyword arguments given.
 98        Basically, this is a proxy around this object_type's get_object() model
 99        method. The ObjectNotExist exception, if thrown, will not be caught,
100        so code that calls this method should catch it.
101        """
102        return self.model_class()._default_manager.using(self._state.db).get(**kwargs)
103
104    def natural_key(self):
105        return (self.app_label, self.model)