django.contrib.contenttypes.models: 92 total statements, 0.0% covered

Generated: Wed 2013-03-13 10:33 CET

Source file: /media/Envs/Envs/filer-gallery/lib/python2.7/site-packages/django/contrib/contenttypes/models.py

Stats: 0 executed, 82 missed, 10 excluded, 77 ignored

  1. from django.db import models
  2. from django.utils.translation import ugettext_lazy as _
  3. from django.utils.encoding import smart_unicode, force_unicode
  4. class ContentTypeManager(models.Manager):
  5. # Cache to avoid re-looking up ContentType objects all over the place.
  6. # This cache is shared by all the get_for_* methods.
  7. _cache = {}
  8. def get_by_natural_key(self, app_label, model):
  9. try:
  10. ct = self.__class__._cache[self.db][(app_label, model)]
  11. except KeyError:
  12. ct = self.get(app_label=app_label, model=model)
  13. self._add_to_cache(self.db, ct)
  14. return ct
  15. def _get_opts(self, model):
  16. return model._meta.concrete_model._meta
  17. def _get_from_cache(self, opts):
  18. key = (opts.app_label, opts.object_name.lower())
  19. return self.__class__._cache[self.db][key]
  20. def get_for_model(self, model):
  21. """
  22. Returns the ContentType object for a given model, creating the
  23. ContentType if necessary. Lookups are cached so that subsequent lookups
  24. for the same model don't hit the database.
  25. """
  26. opts = self._get_opts(model)
  27. try:
  28. ct = self._get_from_cache(opts)
  29. except KeyError:
  30. # Load or create the ContentType entry. The smart_unicode() is
  31. # needed around opts.verbose_name_raw because name_raw might be a
  32. # django.utils.functional.__proxy__ object.
  33. ct, created = self.get_or_create(
  34. app_label = opts.app_label,
  35. model = opts.object_name.lower(),
  36. defaults = {'name': smart_unicode(opts.verbose_name_raw)},
  37. )
  38. self._add_to_cache(self.db, ct)
  39. return ct
  40. def get_for_models(self, *models):
  41. """
  42. Given *models, returns a dictionary mapping {model: content_type}.
  43. """
  44. # Final results
  45. results = {}
  46. # models that aren't already in the cache
  47. needed_app_labels = set()
  48. needed_models = set()
  49. needed_opts = set()
  50. for model in models:
  51. opts = self._get_opts(model)
  52. try:
  53. ct = self._get_from_cache(opts)
  54. except KeyError:
  55. needed_app_labels.add(opts.app_label)
  56. needed_models.add(opts.object_name.lower())
  57. needed_opts.add(opts)
  58. else:
  59. results[model] = ct
  60. if needed_opts:
  61. cts = self.filter(
  62. app_label__in=needed_app_labels,
  63. model__in=needed_models
  64. )
  65. for ct in cts:
  66. model = ct.model_class()
  67. if model._meta in needed_opts:
  68. results[model] = ct
  69. needed_opts.remove(model._meta)
  70. self._add_to_cache(self.db, ct)
  71. for opts in needed_opts:
  72. # These weren't in the cache, or the DB, create them.
  73. ct = self.create(
  74. app_label=opts.app_label,
  75. model=opts.object_name.lower(),
  76. name=smart_unicode(opts.verbose_name_raw),
  77. )
  78. self._add_to_cache(self.db, ct)
  79. results[ct.model_class()] = ct
  80. return results
  81. def get_for_id(self, id):
  82. """
  83. Lookup a ContentType by ID. Uses the same shared cache as get_for_model
  84. (though ContentTypes are obviously not created on-the-fly by get_by_id).
  85. """
  86. try:
  87. ct = self.__class__._cache[self.db][id]
  88. except KeyError:
  89. # This could raise a DoesNotExist; that's correct behavior and will
  90. # make sure that only correct ctypes get stored in the cache dict.
  91. ct = self.get(pk=id)
  92. self._add_to_cache(self.db, ct)
  93. return ct
  94. def clear_cache(self):
  95. """
  96. Clear out the content-type cache. This needs to happen during database
  97. flushes to prevent caching of "stale" content type IDs (see
  98. django.contrib.contenttypes.management.update_contenttypes for where
  99. this gets called).
  100. """
  101. self.__class__._cache.clear()
  102. def _add_to_cache(self, using, ct):
  103. """Insert a ContentType into the cache."""
  104. model = ct.model_class()
  105. key = (model._meta.app_label, model._meta.object_name.lower())
  106. self.__class__._cache.setdefault(using, {})[key] = ct
  107. self.__class__._cache.setdefault(using, {})[ct.id] = ct
  108. class ContentType(models.Model):
  109. name = models.CharField(max_length=100)
  110. app_label = models.CharField(max_length=100)
  111. model = models.CharField(_('python model class name'), max_length=100)
  112. objects = ContentTypeManager()
  113. class Meta:
  114. verbose_name = _('content type')
  115. verbose_name_plural = _('content types')
  116. db_table = 'django_content_type'
  117. ordering = ('name',)
  118. unique_together = (('app_label', 'model'),)
  119. def __unicode__(self):
  120. # self.name is deprecated in favor of using model's verbose_name, which
  121. # can be translated. Formal deprecation is delayed until we have DB
  122. # migration to be able to remove the field from the database along with
  123. # the attribute.
  124. #
  125. # We return self.name only when users have changed its value from the
  126. # initial verbose_name_raw and might rely on it.
  127. model = self.model_class()
  128. if not model or self.name != model._meta.verbose_name_raw:
  129. return self.name
  130. else:
  131. return force_unicode(model._meta.verbose_name)
  132. def model_class(self):
  133. "Returns the Python model class for this type of content."
  134. from django.db import models
  135. return models.get_model(self.app_label, self.model,
  136. only_installed=False)
  137. def get_object_for_this_type(self, **kwargs):
  138. """
  139. Returns an object of this type for the keyword arguments given.
  140. Basically, this is a proxy around this object_type's get_object() model
  141. method. The ObjectNotExist exception, if thrown, will not be caught,
  142. so code that calls this method should catch it.
  143. """
  144. return self.model_class()._base_manager.using(self._state.db).get(**kwargs)
  145. def get_all_objects_for_this_type(self, **kwargs):
  146. """
  147. Returns all objects of this type for the keyword arguments given.
  148. """
  149. return self.model_class()._base_manager.using(self._state.db).filter(**kwargs)
  150. def natural_key(self):
  151. return (self.app_label, self.model)