PageRenderTime 24ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/django/contrib/contenttypes/models.py

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