Debian Codegraph @

src/polymorphic/managers.py

raw
1 """
2 The manager class for use in the models.
3 """
4
5 from __future__ import annotations
6
7 from collections.abc import Iterable
8 from typing import TYPE_CHECKING, Any, Generic, Literal, TypeAlias, cast, overload
9
10 from django.contrib.contenttypes.models import ContentType
11 from django.db import DEFAULT_DB_ALIAS, models, transaction
12 from django.db.models.fields.related_descriptors import (
13 ForwardManyToOneDescriptor,
14 ForwardOneToOneDescriptor,
15 ManyToManyDescriptor,
16 ReverseManyToOneDescriptor,
17 ReverseOneToOneDescriptor,
18 )
19 from typing_extensions import Self, TypeVar
20
21 from polymorphic.query import PolymorphicQuerySet
22
23 if TYPE_CHECKING:
24 from .models import PolymorphicModel # noqa: F401
25
26
27 __all__ = [
28 "PolymorphicManager",
29 "PolymorphicQuerySet",
30 "PolymorphicManyToManyDescriptor",
31 "PolymorphicReverseManyToOneDescriptor",
32 "PolymorphicForwardManyToOneDescriptor",
33 "PolymorphicForwardOneToOneDescriptor",
34 "PolymorphicReverseOneToOneDescriptor",
35 "Nullable",
36 ]
37
38 _All = TypeVar("_All", bound="PolymorphicModel", covariant=True)
39 """
40 This :class:`~typing.TypeVar` represents the union of all possible polymorphic types
41 that a manager may return. All models must derive from
42 :class:`~polymorphic.models.PolymorphicModel`
43 """
44
45 _Base = TypeVar("_Base", bound="PolymorphicModel", default="PolymorphicModel", covariant=True)
46 """
47 This :class:`~typing.TypeVar` represents the base model type from which polymorphic
48 models derive. For managers on a :class:`~polymorphic.models.PolymorphicModel` subclass,
49 you will likely want to use :data:`~typing.Self`.
50 """
51
52 _Through = TypeVar("_Through", bound=models.Model, default=models.Model, covariant=True)
53 """
54 This :class:`~typing.TypeVar` represents the "through" model type for many-to-many
55 relations. By default it is just a regular :class:`~django.db.models.Model`, which
56 will lack the foreign key relations to the linked models.
57 """
58
59 _Nullable = TypeVar("_Nullable", Literal[True], Literal[False], default=Literal[False])
60 """
61 Provided for nullable relations - should be set to ``Literal[True]`` if the relation is
62 nullable, otherwise can be left as the default ``Literal[False]``.
63 """
64
65 _A = TypeVar("_A", bound="PolymorphicModel")
66 _B = TypeVar("_B", bound="PolymorphicModel")
67 _C = TypeVar("_C", bound="PolymorphicModel")
68 _D = TypeVar("_D", bound="PolymorphicModel")
69
70
71 Nullable: TypeAlias = Literal[True]
72 """A more readable type hint alias to indicate that a relation is nullable."""
73
74
75 class PolymorphicManager(models.Manager[_All], Generic[_All, _Base]):
76 """
77 Manager for PolymorphicModel
78
79 Usually not explicitly needed, except if a custom manager or
80 a custom queryset class is to be used.
81 """
82
83 queryset_class: type[PolymorphicQuerySet[_All, _Base]] = PolymorphicQuerySet
84
85 if TYPE_CHECKING:
86
87 def all(self) -> PolymorphicQuerySet[_All, _Base]:
88 return self.get_queryset()
89
90 def filter(self, *args: Any, **kwargs: Any) -> PolymorphicQuerySet[_All, _Base]:
91 return self.get_queryset().filter(*args, **kwargs)
92
93 @classmethod
94 def from_queryset(
95 cls, queryset_class: type[models.query.QuerySet[_All]], class_name: str | None = None
96 ) -> type[Self]:
97 manager = super().from_queryset(queryset_class, class_name=class_name)
98 # also set our version, Django uses _queryset_class
99 manager.queryset_class = queryset_class # type: ignore[assignment]
100 return manager
101
102 def get_queryset(self) -> PolymorphicQuerySet[_All, _Base]:
103 qs = self.queryset_class(self.model, using=self._db, hints=getattr(self, "_hints", None))
104 if self.model._meta.proxy:
105 qs = qs.instance_of(self.model)
106 return qs
107
108 def __str__(self) -> str:
109 return (
110 f"{self.__class__.__name__} (PolymorphicManager) using {self.queryset_class.__name__}"
111 )
112
113 # Proxied methods
114 def non_polymorphic(self) -> PolymorphicQuerySet[_Base, _Base]:
115 return self.all().non_polymorphic()
116
117 # fixme: remove overloads when/if typing ever supports variadic generic unions
118 @overload
119 def instance_of(self, __a: type[_A], /) -> PolymorphicQuerySet[_A, _Base]: ...
120
121 @overload
122 def instance_of(
123 self, __a: type[_A], __b: type[_B], /
124 ) -> PolymorphicQuerySet[_A | _B, _Base]: ...
125
126 @overload
127 def instance_of(
128 self, __a: type[_A], __b: type[_B], __c: type[_C], /
129 ) -> PolymorphicQuerySet[_A | _B | _C, _Base]: ...
130
131 @overload
132 def instance_of(
133 self, __a: type[_A], __b: type[_B], __c: type[_C], __d: type[_D], /
134 ) -> PolymorphicQuerySet[_A | _B | _C | _D, _Base]: ...
135
136 @overload
137 def instance_of(self, *args: type[PolymorphicModel]) -> PolymorphicQuerySet[_All, _Base]: ...
138
139 def instance_of(
140 self: PolymorphicManager[_All], *args: type[PolymorphicModel]
141 ) -> PolymorphicQuerySet[PolymorphicModel, _Base]:
142 return cast(PolymorphicQuerySet["PolymorphicModel", _Base], self.all().instance_of(*args))
143
144 def not_instance_of(self, *args: type[PolymorphicModel]) -> PolymorphicQuerySet[_All, _Base]:
145 return self.all().not_instance_of(*args)
146
147 def get_real_instances(self, base_result_objects: Iterable[_All] | None = None) -> list[_All]:
148 return self.all().get_real_instances(base_result_objects=base_result_objects)
149
150 def create_from_super(self, obj: models.Model, **kwargs: Any) -> _Base:
151 """
152 Create an instance of this manager's model class from the given instance of a
153 parent class.
154
155 This is useful when "promoting" an instance down the inheritance chain.
156
157 :param obj: An instance of a parent class of the manager's model class.
158 :param kwargs: Additional fields to set on the new instance.
159 :return: The newly created instance.
160 """
161 from .models import PolymorphicModel
162
163 with transaction.atomic(using=obj._state.db or DEFAULT_DB_ALIAS):
164 # ensure we have the most derived real instance
165 if isinstance(obj, PolymorphicModel):
166 obj = obj.get_real_instance()
167
168 parent_ptr = self.model._meta.parents.get(type(obj), None)
169
170 if not parent_ptr:
171 raise TypeError(
172 f"{obj.__class__.__name__} is not a direct parent of {self.model.__name__}"
173 )
174 kwargs[parent_ptr.get_attname()] = obj.pk
175
176 # create the new base class with only fields that apply to it.
177 ctype = ContentType.objects.db_manager(
178 using=(obj._state.db or DEFAULT_DB_ALIAS)
179 ).get_for_model(self.model)
180 nobj: _Base = self.model(**kwargs, polymorphic_ctype=ctype) # type: ignore[assignment]
181 nobj.save_base(raw=True, using=obj._state.db or DEFAULT_DB_ALIAS, force_insert=True)
182 # force update the content type, but first we need to
183 # retrieve a clean copy from the db to fill in the null
184 # fields otherwise they would be overwritten.
185 if isinstance(obj, PolymorphicModel):
186 parent = obj.__class__.objects.using(obj._state.db or DEFAULT_DB_ALIAS).get(
187 pk=obj.pk
188 )
189 parent.polymorphic_ctype = ctype
190 parent.save()
191
192 nobj.refresh_from_db() # cast to cls
193 return nobj
194
195
196 if TYPE_CHECKING:
197 from django.db.models.fields.related_descriptors import (
198 ManyRelatedManager,
199 RelatedManager,
200 )
201
202 class PolymorphicManyRelatedManager( # type: ignore[type-var]
203 PolymorphicManager[_All, _Base],
204 ManyRelatedManager[_All, _Through], # pyright: ignore[reportInvalidTypeArguments]
205 Generic[_All, _Base, _Through],
206 ): ...
207
208 class PolymorphicRelatedManager( # type: ignore[type-var]
209 PolymorphicManager[_All, _Base],
210 RelatedManager[_All], # pyright: ignore[reportInvalidTypeArguments]
211 Generic[_All, _Base],
212 ): ...
213
214 else:
215
216 class PolymorphicRelatedManager(PolymorphicManager[_All, _Base], Generic[_All, _Base]): ...
217
218 class PolymorphicManyRelatedManager(
219 PolymorphicManager[_All, _Base],
220 Generic[_All, _Base, _Through],
221 ): ...
222
223
224 class PolymorphicManyToManyDescriptor(ManyToManyDescriptor, Generic[_All, _Base, _Through]):
225 """
226 Use this descriptor class as a type hint for your forward and reverse
227 :class:`~django.db.models.ManyToManyField` relations to/from polymorphic models.
228 For example:
229
230 .. code-block:: python
231
232 to_parents: PolymorphicManyToManyDescriptor[
233 ParentModel | Child1 | Child2, # all possible polymorphic types
234 ParentModel, # the base type (for non_polymorphic)
235 ThroughModel # if custom through model
236 ] = models.ManyToManyField( # type: ignore[assignment]
237 "ParentModel",
238 related_name="to_parents_reverse"
239 )
240
241 """
242
243 @overload # type: ignore[override]
244 def __get__(self, instance: None, cls: Any | None = None, /) -> Self: ...
245
246 @overload
247 def __get__(
248 self, instance: models.Model, cls: Any | None = None, /
249 ) -> PolymorphicManyRelatedManager[_All, _Base, _Through]: ...
250
251 def __get__(
252 self, instance: models.Model | None, cls: Any | None = None, /
253 ) -> Self | PolymorphicManyRelatedManager[_All, _Base, _Through]:
254 return cast( # pragma: no cover
255 Self | PolymorphicManyRelatedManager[_All, _Base, _Through],
256 super().__get__(instance, cls),
257 )
258
259
260 class PolymorphicReverseManyToOneDescriptor(
261 ReverseManyToOneDescriptor,
262 Generic[_All, _Base],
263 ):
264 """
265 Use this descriptor class as a type hint for your reverse
266 :class:`~django.db.models.ForeignKey` relations to polymorphic models. For example:
267
268
269 .. code-block:: python
270
271 class ParentModel(PolymorphicModel):
272 models.ForeignKey(
273 RelatedModel,
274 on_delete=models.CASCADE,
275 null=True,
276 related_name="reverse"
277 )
278
279 class RelatedModel(models.Model):
280
281 reverse: PolymorphicReverseManyToOneDescriptor[
282 ParentModel | Child1 | Child2,
283 ParentModel
284 ]
285 """
286
287 @overload
288 def __get__(self, instance: None, cls: Any | None = None, /) -> Self: ...
289
290 @overload
291 def __get__(
292 self, instance: models.Model, cls: Any | None = None, /
293 ) -> PolymorphicRelatedManager[_All, _Base]: ...
294
295 def __get__(
296 self, instance: models.Model | None, cls: Any | None = None, /
297 ) -> Self | PolymorphicRelatedManager[_All, _Base]:
298 return cast( # pragma: no cover
299 Self | PolymorphicRelatedManager[_All, _Base], super().__get__(instance, cls)
300 )
301
302
303 class PolymorphicForwardManyToOneDescriptor(
304 ForwardManyToOneDescriptor,
305 Generic[_All, _Base, _Nullable],
306 ):
307 """
308 Use this descriptor class as a type hint for your
309 :class:`~django.db.models.ForeignKey` relations to polymorphic models. For example:
310
311 .. note::
312
313 Your typing system will likely flag an assignment error on the class attribute
314 - this is unfortunate but unavoidable - we suggest you add a
315 `# type: ignore[assignment]`.
316
317 .. code-block:: python
318
319 parent: PolymorphicForwardManyToOneDescriptor[
320 ParentModel | Child1 | Child2,
321 ParentModel,
322 Nullable,
323 ] = models.ForeignKey(
324 ParentModel,
325 on_delete=models.CASCADE,
326 null=True,
327 )
328 """
329
330 @overload # type: ignore[override]
331 def __get__(self, instance: None, cls: Any | None = None, /) -> Self: ...
332
333 @overload
334 def __get__(
335 self: PolymorphicForwardManyToOneDescriptor[_All, _Base, Literal[False]],
336 instance: models.Model,
337 cls: Any | None = None,
338 /,
339 ) -> _All: ...
340
341 @overload
342 def __get__(
343 self: PolymorphicForwardManyToOneDescriptor[_All, _Base, Literal[True]],
344 instance: models.Model,
345 cls: Any | None = None,
346 /,
347 ) -> _All | None: ...
348
349 def __get__(
350 self, instance: models.Model | None, cls: Any | None = None, /
351 ) -> Self | _All | None:
352 return cast( # pragma: no cover
353 Self | _All | None, super().__get__(instance, cls)
354 )
355
356 def get_queryset( # type: ignore[override]
357 self, *, instance: models.Model
358 ) -> PolymorphicQuerySet[_All, _Base]:
359 # keyword-only instance is the only calling convention accepted by every
360 # supported Django version (required by the >= 6.1 signature)
361 return cast( # pragma: no cover
362 PolymorphicQuerySet[_All, _Base],
363 super().get_queryset(instance=instance),
364 )
365
366
367 class PolymorphicForwardOneToOneDescriptor(
368 ForwardOneToOneDescriptor,
369 PolymorphicForwardManyToOneDescriptor[_All, _Base, _Nullable],
370 Generic[_All, _Base, _Nullable],
371 ):
372 """
373 Use this descriptor class as a type hint for your
374 :class:`~django.db.models.OneToOneField` relations to polymorphic models. For
375 example:
376
377 .. note::
378
379 Your typing system will likely flag an assignment error on the class attribute
380 - this is unfortunate but unavoidable - we suggest you add a
381 `# type: ignore[assignment]`.
382
383 .. code-block:: python
384
385 parent: PolymorphicForwardOneToOneDescriptor[
386 ParentModel | Child1 | Child2,
387 ParentModel,
388 Nullable,
389 ] = models.OneToOneField(
390 ParentModel,
391 on_delete=models.CASCADE,
392 null=True,
393 )
394 """
395
396
397 class PolymorphicReverseOneToOneDescriptor(
398 ReverseOneToOneDescriptor,
399 Generic[_All, _Base, _Nullable],
400 ):
401 """
402 Use this descriptor class as a type hint for your reverse
403 :class:`~django.db.models.OneToOneField` relations to polymorphic models. For
404 example:
405
406 .. code-block:: python
407
408 class ParentModel(PolymorphicModel):
409 models.OneToOneField(
410 RelatedModel,
411 on_delete=models.CASCADE,
412 null=True,
413 related_name="reverse"
414 )
415
416 class RelatedModel(models.Model):
417
418 reverse: PolymorphicReverseOneToOneDescriptor[
419 ParentModel | Child1 | Child2,
420 ParentModel,
421 Nullable,
422 ]
423 """
424
425 @overload
426 def __get__(self, instance: None, cls: Any | None = None, /) -> Self: ...
427
428 @overload
429 def __get__(
430 self: PolymorphicReverseOneToOneDescriptor[_All, _Base, Literal[False]],
431 instance: models.Model,
432 cls: Any | None = None,
433 /,
434 ) -> _All: ...
435
436 @overload
437 def __get__(
438 self: PolymorphicReverseOneToOneDescriptor[_All, _Base, Literal[True]],
439 instance: models.Model,
440 cls: Any | None = None,
441 /,
442 ) -> _All | None: ...
443
444 def __get__(
445 self, instance: models.Model | None, cls: Any | None = None, /
446 ) -> Self | _All | None:
447 return cast( # pragma: no cover
448 Self | _All | None, super().__get__(instance, cls)
449 )
450
451 def get_queryset( # type: ignore[override]
452 self, *, instance: models.Model
453 ) -> PolymorphicQuerySet[_All, _Base]:
454 # keyword-only instance is the only calling convention accepted by every
455 # supported Django version (required by the >= 6.1 signature)
456 return cast( # pragma: no cover
457 PolymorphicQuerySet[_All, _Base],
458 super().get_queryset(instance=instance),
459 )