Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

models.py 6.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. from collections import defaultdict
  2. from django.apps import apps
  3. from django.db import models
  4. from django.utils.translation import gettext_lazy as _
  5. class ContentTypeManager(models.Manager):
  6. use_in_migrations = True
  7. def __init__(self, *args, **kwargs):
  8. super().__init__(*args, **kwargs)
  9. # Cache shared by all the get_for_* methods to speed up
  10. # ContentType retrieval.
  11. self._cache = {}
  12. def get_by_natural_key(self, app_label, model):
  13. try:
  14. ct = self._cache[self.db][(app_label, model)]
  15. except KeyError:
  16. ct = self.get(app_label=app_label, model=model)
  17. self._add_to_cache(self.db, ct)
  18. return ct
  19. def _get_opts(self, model, for_concrete_model):
  20. if for_concrete_model:
  21. model = model._meta.concrete_model
  22. return model._meta
  23. def _get_from_cache(self, opts):
  24. key = (opts.app_label, opts.model_name)
  25. return self._cache[self.db][key]
  26. def get_for_model(self, model, for_concrete_model=True):
  27. """
  28. Return the ContentType object for a given model, creating the
  29. ContentType if necessary. Lookups are cached so that subsequent lookups
  30. for the same model don't hit the database.
  31. """
  32. opts = self._get_opts(model, for_concrete_model)
  33. try:
  34. return self._get_from_cache(opts)
  35. except KeyError:
  36. pass
  37. # The ContentType entry was not found in the cache, therefore we
  38. # proceed to load or create it.
  39. try:
  40. # Start with get() and not get_or_create() in order to use
  41. # the db_for_read (see #20401).
  42. ct = self.get(app_label=opts.app_label, model=opts.model_name)
  43. except self.model.DoesNotExist:
  44. # Not found in the database; we proceed to create it. This time
  45. # use get_or_create to take care of any race conditions.
  46. ct, created = self.get_or_create(
  47. app_label=opts.app_label,
  48. model=opts.model_name,
  49. )
  50. self._add_to_cache(self.db, ct)
  51. return ct
  52. def get_for_models(self, *models, for_concrete_models=True):
  53. """
  54. Given *models, return a dictionary mapping {model: content_type}.
  55. """
  56. results = {}
  57. # Models that aren't already in the cache.
  58. needed_app_labels = set()
  59. needed_models = set()
  60. # Mapping of opts to the list of models requiring it.
  61. needed_opts = defaultdict(list)
  62. for model in models:
  63. opts = self._get_opts(model, for_concrete_models)
  64. try:
  65. ct = self._get_from_cache(opts)
  66. except KeyError:
  67. needed_app_labels.add(opts.app_label)
  68. needed_models.add(opts.model_name)
  69. needed_opts[opts].append(model)
  70. else:
  71. results[model] = ct
  72. if needed_opts:
  73. # Lookup required content types from the DB.
  74. cts = self.filter(
  75. app_label__in=needed_app_labels,
  76. model__in=needed_models
  77. )
  78. for ct in cts:
  79. model = ct.model_class()
  80. opts_models = needed_opts.pop(ct.model_class()._meta, [])
  81. for model in opts_models:
  82. results[model] = ct
  83. self._add_to_cache(self.db, ct)
  84. # Create content types that weren't in the cache or DB.
  85. for opts, opts_models in needed_opts.items():
  86. ct = self.create(
  87. app_label=opts.app_label,
  88. model=opts.model_name,
  89. )
  90. self._add_to_cache(self.db, ct)
  91. for model in opts_models:
  92. results[model] = ct
  93. return results
  94. def get_for_id(self, id):
  95. """
  96. Lookup a ContentType by ID. Use the same shared cache as get_for_model
  97. (though ContentTypes are obviously not created on-the-fly by get_by_id).
  98. """
  99. try:
  100. ct = self._cache[self.db][id]
  101. except KeyError:
  102. # This could raise a DoesNotExist; that's correct behavior and will
  103. # make sure that only correct ctypes get stored in the cache dict.
  104. ct = self.get(pk=id)
  105. self._add_to_cache(self.db, ct)
  106. return ct
  107. def clear_cache(self):
  108. """
  109. Clear out the content-type cache.
  110. """
  111. self._cache.clear()
  112. def _add_to_cache(self, using, ct):
  113. """Insert a ContentType into the cache."""
  114. # Note it's possible for ContentType objects to be stale; model_class() will return None.
  115. # Hence, there is no reliance on model._meta.app_label here, just using the model fields instead.
  116. key = (ct.app_label, ct.model)
  117. self._cache.setdefault(using, {})[key] = ct
  118. self._cache.setdefault(using, {})[ct.id] = ct
  119. class ContentType(models.Model):
  120. app_label = models.CharField(max_length=100)
  121. model = models.CharField(_('python model class name'), max_length=100)
  122. objects = ContentTypeManager()
  123. class Meta:
  124. verbose_name = _('content type')
  125. verbose_name_plural = _('content types')
  126. db_table = 'django_content_type'
  127. unique_together = (('app_label', 'model'),)
  128. def __str__(self):
  129. return self.name
  130. @property
  131. def name(self):
  132. model = self.model_class()
  133. if not model:
  134. return self.model
  135. return str(model._meta.verbose_name)
  136. def model_class(self):
  137. """Return the model class for this type of content."""
  138. try:
  139. return apps.get_model(self.app_label, self.model)
  140. except LookupError:
  141. return None
  142. def get_object_for_this_type(self, **kwargs):
  143. """
  144. Return an object of this type for the keyword arguments given.
  145. Basically, this is a proxy around this object_type's get_object() model
  146. method. The ObjectNotExist exception, if thrown, will not be caught,
  147. so code that calls this method should catch it.
  148. """
  149. return self.model_class()._base_manager.using(self._state.db).get(**kwargs)
  150. def get_all_objects_for_this_type(self, **kwargs):
  151. """
  152. Return all objects of this type for the keyword arguments given.
  153. """
  154. return self.model_class()._base_manager.using(self._state.db).filter(**kwargs)
  155. def natural_key(self):
  156. return (self.app_label, self.model)