Debian Codegraph @

django/contrib/contenttypes/models.py

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