Debian Codegraph @

src/polymorphic/utils.py

raw
1 from __future__ import annotations
2
3 from collections import defaultdict
4 from dataclasses import dataclass
5 from functools import lru_cache
6 from typing import Any, cast
7
8 from django.apps import apps
9 from django.contrib.contenttypes.models import ContentType
10 from django.core.exceptions import FieldError
11 from django.db import DEFAULT_DB_ALIAS, models
12 from django.db.models import Model, Q, Subquery
13
14
15 @dataclass(frozen=True)
16 class ParentLinkInfo:
17 """
18 Information about a parent table link in a polymorphic model.
19 """
20
21 model: type[models.Model]
22 link: models.Field[Any, Any]
23
24
25 def reset_polymorphic_ctype(*models: type[models.Model], **filters: Any) -> None:
26 """
27 Set the polymorphic content-type ID field to the proper model
28 Sort the ``*models`` from base class to descending class,
29 to make sure the content types are properly assigned.
30
31 Add ``ignore_existing=True`` to skip models which already
32 have a polymorphic content type.
33 """
34 using = filters.pop("using", DEFAULT_DB_ALIAS)
35 ignore_existing = filters.pop("ignore_existing", False)
36
37 models_list: list[type[Model]] = sort_by_subclass(*models)
38 if ignore_existing:
39 # When excluding models, make sure we don't ignore the models we
40 # just assigned the an content type to. hence, start with child first.
41 models_list = list(reversed(models_list))
42
43 for new_model in models_list:
44 new_ct = ContentType.objects.db_manager(using).get_for_model(
45 new_model, for_concrete_model=False
46 )
47
48 qs = new_model.objects.db_manager(using) # type: ignore[attr-defined]
49 if ignore_existing:
50 qs = qs.filter(polymorphic_ctype__isnull=True)
51 if filters:
52 qs = qs.filter(**filters)
53 qs.update(polymorphic_ctype=new_ct)
54
55
56 def _compare_mro(cls1: type, cls2: type) -> int:
57 if cls1 is cls2:
58 return 0
59
60 try:
61 index1 = cls1.mro().index(cls2)
62 except ValueError:
63 return -1 # cls2 not inherited by 1
64
65 try:
66 index2 = cls2.mro().index(cls1)
67 except ValueError:
68 return 1 # cls1 not inherited by 2
69
70 return (index1 > index2) - (index1 < index2) # python 3 compatible cmp. # pragma: no cover
71
72
73 def sort_by_subclass(*classes: type[models.Model]) -> list[type[models.Model]]:
74 """
75 Sort a series of models by their inheritance order.
76 """
77 from functools import cmp_to_key
78
79 return sorted(classes, key=cmp_to_key(_compare_mro))
80
81
82 @lru_cache(maxsize=None)
83 def get_base_polymorphic_model(
84 ChildModel: type[models.Model], allow_abstract: bool = False
85 ) -> type[models.Model] | None:
86 """
87 First the first concrete model in the inheritance chain that inherited from the
88 PolymorphicModel.
89 """
90 from polymorphic.models import PolymorphicModel
91
92 for base_class in reversed(ChildModel.mro()):
93 if (
94 issubclass(base_class, PolymorphicModel)
95 and base_class is not PolymorphicModel
96 and (allow_abstract or not base_class._meta.abstract)
97 ):
98 return base_class
99 return None
100
101
102 @lru_cache(maxsize=None)
103 def route_to_ancestor(
104 model_class: type[models.Model], ancestor_model: type[models.Model]
105 ) -> list[ParentLinkInfo]:
106 """
107 Returns the first (highest mro precedence - depth first on parents) model
108 inheritance route to the given ancestor model - or an empty list if no such
109 route exists. Results are cached
110
111 .. warning::
112
113 This only works for concrete ancestors!
114
115 Returns a :class:`list` of :class:`ParentLinkInfo`
116 """
117 route: list[ParentLinkInfo] = []
118
119 def find_route(
120 model: type[models.Model],
121 target_model: type[models.Model],
122 current_route: list[ParentLinkInfo],
123 ) -> list[ParentLinkInfo] | None:
124 if model is target_model:
125 return current_route
126
127 for parent_model, field_to_parent in model._meta.parents.items():
128 if field_to_parent is not None:
129 new_route = current_route + [ParentLinkInfo(parent_model, field_to_parent)]
130 found_route = find_route(parent_model, target_model, new_route)
131 if found_route is not None:
132 return found_route
133 else:
134 return find_route(parent_model, target_model, current_route)
135 return None
136
137 found_route = find_route(model_class, ancestor_model, route)
138 if found_route is None:
139 return []
140 return found_route
141
142
143 def is_model_loaded(model: type[models.Model]) -> bool:
144 try:
145 apps.get_model(model._meta.app_label, model._meta.model_name)
146 return True
147 except LookupError:
148 return False
149
150
151 @lru_cache(maxsize=None)
152 def concrete_descendants(
153 model_class: type[models.Model], include_proxy: bool = False
154 ) -> list[type[models.Model]]:
155 """
156 Get a list of all concrete (non-abstract, non-proxy) descendant model classes in
157 tree order with leaf descendants last. Results are cached.
158 """
159 from django.apps import apps
160
161 apps.check_models_ready()
162
163 def add_concrete_descendants(
164 model: type[models.Model], result: list[type[models.Model]]
165 ) -> None:
166 """Add concrete descendants in tree order (ancestors before descendants)."""
167 for sub_cls in model.__subclasses__():
168 # Add concrete models in pre-order (parent before children)
169 if not sub_cls._meta.abstract and (include_proxy or not sub_cls._meta.proxy):
170 if is_model_loaded(sub_cls):
171 result.append(sub_cls)
172
173 # Always recurse to find descendants through abstract and proxy models
174 add_concrete_descendants(sub_cls, result)
175
176 result: list[type[models.Model]] = []
177 add_concrete_descendants(model_class, result)
178 return result
179
180
181 def prepare_for_copy(obj: models.Model) -> None:
182 """
183 Prepare a model instance for copying by resetting all primary keys and parent table
184 pointers in the inheritance chain. **Copy semantics are application specific.** This
185 function only resets the fields required to create a new instance when saved, it
186 does not deep copy related objects or save the new instance
187 (See :ref:`copying discussion in the Django documentation.
188 <topics/db/queries:copying model instances>`):
189
190 .. code-block:: python
191
192 from polymorphic.utils import prepare_for_copy
193
194 original = YourModel.objects.get(pk=1)
195 prepare_for_copy(original)
196 # update any related fields here as needed
197 original.save() # creates a new object in the database
198
199 .. tip::
200
201 Preparation is at the inheritance level of the passed in model. This means you
202 can copy and upcast at the same time. Suppose you have A->B->C inheritance chain,
203 and you have an instance of C that you want to copy as a B instance:
204
205 .. code-block:: python
206
207 c = C.objects.create()
208 c_as_b = B.objects.non_polymorphic().get(pk=c.pk)
209
210 # copy c as a b instance
211 prepare_for_copy(c_as_b)
212 c_as_b.save()
213
214 assert B.objects.count() == 2
215 assert C.objects.count() == 1
216
217 If you want polymorphic copying instead:
218
219 .. code-block:: python
220
221 prepare_for_copy(b_instance.get_real_instance())
222
223 **This function also works for non-polymorphic multi-table models.**
224
225 :param obj: The model instance to prepare for copying.
226 """
227 from polymorphic.models import PolymorphicModel
228
229 obj.pk = None
230 if isinstance(obj, PolymorphicModel):
231 # we might be upcasting - allow ctype to be reset automatically on save
232 obj.polymorphic_ctype_id = None
233
234 def reset_parent_pointers(mdl):
235 """
236 Reset all parent table pointers and pks in the inheritance chain.
237 """
238 for parent, ptr in mdl._meta.parents.items():
239 reset_parent_pointers(parent)
240 if ptr is not None:
241 setattr(obj, ptr.attname, None)
242 setattr(obj, parent._meta.pk.attname, None)
243
244 reset_parent_pointers(obj)
245 obj._state.adding = True # Mark as new object
246
247
248 def _lazy_ctype(model: type[models.Model], using: str = DEFAULT_DB_ALIAS) -> ContentType | Q:
249 mgr = ContentType.objects.db_manager(using=using)
250 if apps.models_ready and (
251 cid := mgr._cache.get(using, {}).get((model._meta.app_label, model._meta.model_name)) # type: ignore[attr-defined]
252 ):
253 # cast needed because _cache returns Any
254 return cast(ContentType, cid)
255 return Q(app_label=model._meta.app_label) & Q(model=model._meta.model_name)
256
257
258 def lazy_ctype(model: type[models.Model], using: str = DEFAULT_DB_ALIAS) -> ContentType | Subquery:
259 """
260 Return the content type id for the given model class if it is in the cache,
261 otherwise return a subquery that can be used to match the content type as part
262 of a larger query. Safe to call before apps are fully loaded.
263
264 :param model: The model class to get the content type for.
265 :return: The content type for the model class.
266 :rtype: ContentType object or Subquery
267 """
268 ctype = _lazy_ctype(model, using=using)
269 return (
270 ctype
271 if isinstance(ctype, ContentType)
272 else Subquery(ContentType.objects.db_manager(using=using).filter(ctype).values("pk")[:1])
273 )
274
275
276 @lru_cache(maxsize=None)
277 def _map_queryname_to_class(base_model: type[models.Model], qry_name: str) -> type[models.Model]:
278 """Try to match a model name in a query to a model class"""
279 name_map: dict[str, list[type[models.Model]]] = defaultdict(list)
280 name_map[base_model.__name__.lower()].append(base_model)
281 for cls in concrete_descendants(base_model, include_proxy=True):
282 name_map[cls.__name__.lower()].append(cls)
283
284 matches = name_map.get(qry_name.lower(), [])
285 if len(matches) == 1:
286 return matches[0]
287 elif len(matches) > 1:
288 raise FieldError(
289 f"{qry_name} could refer to any of {[m._meta.label for m in matches]}. In "
290 f"this case, please use the syntax: applabel__ModelName___field"
291 )
292
293 # FIXME: raise a FieldError - upstream code currently relies on this AssertionError
294 # and it will be thrown in legitimate cases because this function ends up being
295 # called on subclasses of the original query model in _get_real_instances. That
296 # code should be refactored to avoiid this.
297 raise AssertionError(f"{qry_name} is not a subclass of {base_model._meta.label}")
298
299
300 def _clear_utility_caches() -> None:
301 """Clear all lru_cache caches in this module."""
302 get_base_polymorphic_model.cache_clear()
303 route_to_ancestor.cache_clear()
304 concrete_descendants.cache_clear()
305 _map_queryname_to_class.cache_clear()