Debian Codegraph @

src/polymorphic/models.py

raw
1 """
2 Seamless Polymorphic Inheritance for Django Models
3 """
4
5 from __future__ import annotations
6
7 import warnings
8 from collections.abc import Iterable
9 from typing import ClassVar, cast
10
11 from django.contrib.contenttypes.models import ContentType
12 from django.db import models, router, transaction
13 from django.db.models import Q
14 from django.db.models.base import ModelBase
15 from django.db.utils import DEFAULT_DB_ALIAS
16 from django.utils.functional import classproperty
17 from typing_extensions import Self
18
19 from .base import PolymorphicModelBase
20 from .managers import PolymorphicManager
21 from .query_translate import translate_polymorphic_Q_object
22 from .utils import get_base_polymorphic_model, lazy_ctype
23
24 ###################################################################################
25 # PolymorphicModel
26
27
28 class PolymorphicTypeUndefined(LookupError): ...
29
30
31 class PolymorphicTypeInvalid(RuntimeError): ...
32
33
34 class PolymorphicModel(models.Model, metaclass=PolymorphicModelBase):
35 """
36 Abstract base class that provides polymorphic behaviour
37 for any model directly or indirectly derived from it.
38
39 PolymorphicModel declares one field for internal use (:attr:`polymorphic_ctype`)
40 and provides a polymorphic manager as the default manager (and as 'objects').
41 """
42
43 _meta_skip: ClassVar[bool] = True
44
45 # for PolymorphicModelBase, so it can tell which models are polymorphic and which are not (duck typing)
46 polymorphic_model_marker: ClassVar[bool] = True
47
48 # for PolymorphicQuery, True => an overloaded __repr__ with nicer multi-line output is used by PolymorphicQuery
49 polymorphic_query_multiline_output: ClassVar[bool] = False
50
51 # avoid ContentType related field accessor clash (an error emitted by model validation)
52 #: The model field that stores the :class:`~django.contrib.contenttypes.models.ContentType` reference to the actual class.
53 polymorphic_ctype: models.ForeignKey[ContentType | None, ContentType | None] = (
54 models.ForeignKey(
55 ContentType,
56 null=True,
57 editable=False,
58 on_delete=models.CASCADE,
59 related_name="polymorphic_%(app_label)s.%(class)s_set+",
60 )
61 )
62
63 # some applications want to know the name of the fields that are added to its models
64 polymorphic_internal_model_fields: ClassVar[list[str]] = ["polymorphic_ctype"]
65
66 objects: ClassVar[PolymorphicManager[Self]] = PolymorphicManager()
67
68 class Meta:
69 abstract: ClassVar[bool] = True
70
71 @classproperty
72 def polymorphic_primary_key_name(cls) -> str:
73 """
74 The name of the root primary key field of this polymorphic inheritance chain.
75 """
76 warnings.warn(
77 "polymorphic_primary_key_name is deprecated and will be removed in "
78 "version 5.0, use get_base_polymorphic_model(Model)._meta.pk.attname "
79 "instead.",
80 DeprecationWarning,
81 stacklevel=2,
82 )
83 base_model = get_base_polymorphic_model(cls, allow_abstract=True)
84 assert base_model is not None, "Polymorphic model must have a base"
85 return base_model._meta.pk.attname
86
87 @classmethod
88 def translate_polymorphic_Q_object(cls, q: Q) -> Q:
89 return translate_polymorphic_Q_object(cls, q)
90
91 def pre_save_polymorphic(self, using: str = DEFAULT_DB_ALIAS) -> None:
92 """
93 Make sure the ``polymorphic_ctype`` value is correctly set on this model.
94
95 This method automatically updates the polymorphic_ctype when:
96 - The object is being saved for the first time
97 - The object is being saved to a different database than it was loaded from
98
99 This ensures cross-database saves work correctly without ForeignKeyViolation.
100 """
101 # This function may be called manually in special use-cases. When the object
102 # is saved for the first time, we store its real class in polymorphic_ctype.
103 # When the object later is retrieved by PolymorphicQuerySet, it uses this
104 # field to figure out the real class of this object
105 # (used by PolymorphicQuerySet._get_real_instances)
106
107 # Update polymorphic_ctype if:
108 # 1. It's not set yet (new object), OR
109 # 2. The database has changed (cross-database save)
110 needs_update = not self.polymorphic_ctype_id or (
111 self._state.db and self._state.db != using
112 )
113
114 if needs_update:
115 # Set polymorphic_ctype_id directly to avoid database router issues
116 # when saving across databases
117 ctype = ContentType.objects.db_manager(using).get_for_model(
118 self, for_concrete_model=False
119 )
120 self.polymorphic_ctype_id = ctype.pk
121
122 def save(
123 self,
124 force_insert: bool | tuple[ModelBase, ...] = False,
125 force_update: bool = False,
126 using: str | None = None,
127 update_fields: Iterable[str] | None = None,
128 **kwargs,
129 ) -> None:
130 """Calls :meth:`pre_save_polymorphic` and saves the model."""
131 # Determine the database to use via Django's routing infrastructure:
132 # 1. Explicit 'using' parameter takes precedence
133 # 2. Otherwise consult DATABASE_ROUTERS via router.db_for_write()
134 # 3. The router falls back to _state.db, then DEFAULT_DB_ALIAS
135 self.pre_save_polymorphic(
136 using=(
137 using
138 or router.db_for_write(self.__class__, instance=self)
139 or self._state.db
140 or DEFAULT_DB_ALIAS
141 )
142 )
143 return super().save(
144 force_insert=force_insert,
145 force_update=force_update,
146 using=using,
147 update_fields=update_fields,
148 **kwargs,
149 )
150
151 save.alters_data = True # type: ignore[attr-defined]
152
153 def get_real_instance_class(self) -> type[Self] | None:
154 """
155 Return the actual model type of the object.
156
157 If a non-polymorphic manager (like base_objects) has been used to
158 retrieve objects, then the real class/type of these objects may be
159 determined using this method.
160 """
161 if self.polymorphic_ctype_id is None:
162 raise PolymorphicTypeUndefined(
163 f"The model {self.__class__.__name__}#{self.pk} does not have a `polymorphic_ctype_id` value defined.\n"
164 f"If you created models outside polymorphic, e.g. through an import or migration, "
165 f"make sure the `polymorphic_ctype_id` field points to the ContentType ID of the model subclass."
166 )
167
168 # the following line would be the easiest way to do this, but it produces sql queries
169 # return self.polymorphic_ctype.model_class()
170 # so we use the following version, which uses the ContentType manager cache.
171 # Note that model_class() can return None for stale content types;
172 # when the content type record still exists but no longer refers to an existing model.
173 model = (
174 ContentType.objects.db_manager(self._state.db)
175 .get_for_id(self.polymorphic_ctype_id)
176 .model_class()
177 )
178
179 # Protect against bad imports (dumpdata without --natural) or other
180 # issues missing with the ContentType models.
181 if (
182 model is not None
183 and not issubclass(model, self.__class__)
184 and (
185 self.__class__._meta.proxy_for_model is None
186 or not issubclass(model, self.__class__._meta.proxy_for_model)
187 )
188 ):
189 raise PolymorphicTypeInvalid(
190 f"ContentType {self.polymorphic_ctype_id} for {model} #{self.pk} does "
191 "not point to a subclass!"
192 )
193
194 return cast(type[Self] | None, model)
195
196 def get_real_concrete_instance_class_id(self) -> int | None:
197 model_class = self.get_real_instance_class()
198 if model_class is None:
199 return None
200 return (
201 ContentType.objects.db_manager(self._state.db)
202 .get_for_model(model_class, for_concrete_model=True)
203 .pk
204 )
205
206 def get_real_concrete_instance_class(self) -> type[Self] | None:
207 model_class = self.get_real_instance_class()
208 if model_class is None:
209 return None
210 return cast(
211 type[Self] | None,
212 ContentType.objects.db_manager(self._state.db)
213 .get_for_model(model_class, for_concrete_model=True)
214 .model_class(),
215 )
216
217 def get_real_instance(self) -> Self:
218 """
219 Upcast an object to it's actual type.
220
221 If a non-polymorphic manager (like base_objects) has been used to
222 retrieve objects, then the complete object with it's real class/type
223 and all fields may be retrieved with this method.
224
225 If the model of the object's actual type does not exist (i.e. its
226 ContentType is stale), this method raises a
227 :class:`~polymorphic.models.PolymorphicTypeInvalid` exception.
228
229 .. note::
230 Each method call executes one db query (if necessary).
231 Use the :meth:`~polymorphic.managers.PolymorphicQuerySet.get_real_instances`
232 to upcast a complete list in a single efficient query.
233 """
234 real_model = self.get_real_instance_class()
235 if real_model is self.__class__:
236 return self
237 if real_model is None:
238 raise PolymorphicTypeInvalid(
239 f"ContentType {self.polymorphic_ctype_id} for {self.__class__} "
240 f"#{self.pk} does not have a corresponding model!"
241 )
242 return self.__class__.objects.db_manager(self._state.db).get(pk=self.pk)
243
244 def delete(
245 self, using: str | None = None, keep_parents: bool = False
246 ) -> tuple[int, dict[str, int]]:
247 """
248 Behaves the same as Django's default :meth:`~django.db.models.Model.delete()`,
249 but with support for upcasting when ``keep_parents`` is True. When keeping
250 parents (upcasting the row) the ``polymorphic_ctype`` fields of the parent rows
251 are updated accordingly in a transaction with the child row deletion.
252 """
253 # if we are keeping parents, we must first determine which polymorphic_ctypes we
254 # need to update
255 parent_updates = (
256 [
257 (parent_model, getattr(self, parent_field.get_attname())) # type: ignore[union-attr]
258 for parent_model, parent_field in self._meta.parents.items()
259 if issubclass(parent_model, PolymorphicModel)
260 ]
261 if keep_parents
262 else []
263 )
264 if parent_updates:
265 with transaction.atomic(using=using):
266 # If keeping the parents (upcasting) we need to update the relevant
267 # content types for all parent inheritance paths.
268 ret = super().delete(using=using, keep_parents=keep_parents)
269 for parent_model, pk in parent_updates:
270 parent_model.objects.db_manager(using=using).non_polymorphic().filter(
271 pk=pk
272 ).update(
273 polymorphic_ctype=lazy_ctype(parent_model, using=using or DEFAULT_DB_ALIAS)
274 )
275 return ret
276 return super().delete(using=using, keep_parents=keep_parents)
277
278 delete.alters_data = True # type: ignore[attr-defined]