Debian Codegraph @

src/polymorphic/base.py

raw
1 """
2 PolymorphicModel Meta Class
3 """
4
5 import sys
6 import warnings
7 from typing import Any, cast
8
9 from django.db import models
10 from django.db.models.base import ModelBase
11 from django.db.models.options import Options
12
13 from .deletion import PolymorphicGuard
14 from .managers import PolymorphicManager
15 from .related_descriptors import (
16 NonPolymorphicForwardOneToOneDescriptor,
17 NonPolymorphicReverseOneToOneDescriptor,
18 )
19 from .utils import _clear_utility_caches
20
21 # PolymorphicQuerySet Q objects (and filter()) support these additional key words.
22 # These are forbidden as field names (a descriptive exception is raised)
23 POLYMORPHIC_SPECIAL_Q_KWORDS: set[str] = {"instance_of", "not_instance_of"}
24
25
26 class ManagerInheritanceWarning(RuntimeWarning):
27 pass
28
29
30 # check that we're on cpython to enable dumpdata frame inspection guard
31 check_dump: bool = hasattr(sys, "_getframe")
32
33
34 # We wrap the base_manager property to return a PolymorphicManager
35 # for polymorphic models when the base manager would otherwise
36 # be the default auto-created manager. This ensures that
37 # reverse relations to polymorphic models also use polymorphic
38 # querysets by default.
39 # https://github.com/jazzband/django-polymorphic/pull/858
40 dj_base_manager = Options.base_manager.func # type: ignore[attr-defined]
41
42
43 def polymorphic_base_manager(self):
44 """
45 Return a polymorphic base manager for polymorphic models.
46 """
47 from polymorphic.models import PolymorphicModel
48
49 mgr = dj_base_manager(self)
50 if (
51 issubclass(self.model, PolymorphicModel)
52 and mgr.__class__ is models.Manager
53 and mgr.auto_created
54 ):
55 manager: PolymorphicManager = PolymorphicManager()
56 manager.name = "_base_manager"
57 manager.model = self.model
58 manager.auto_created = True
59 return manager
60 return mgr
61
62
63 setattr(Options.base_manager, "func", polymorphic_base_manager)
64
65
66 class PolymorphicModelBase(ModelBase):
67 """
68 Manager inheritance is a pretty complex topic which may need
69 more thought regarding how this should be handled for polymorphic
70 models.
71
72 In any case, we probably should propagate 'objects' and 'base_objects'
73 from PolymorphicModel to every subclass. We also want to somehow
74 inherit/propagate _default_manager as well, as it needs to be polymorphic.
75
76 The current implementation below is an experiment to solve this
77 problem with a very simplistic approach: We unconditionally
78 inherit/propagate any and all managers (using _copy_to_model),
79 as long as they are defined on polymorphic models
80 (the others are left alone).
81
82 Like Django ModelBase, we special-case _default_manager:
83 if there are any user-defined managers, it is set to the first of these.
84
85 We also require that _default_manager as well as any user defined
86 polymorphic managers produce querysets that are derived from
87 PolymorphicQuerySet.
88
89 We also replace the parent/child relation field descriptors with versions that will
90 use non-polymorphic querysets.
91
92 If we have inheritance of the form ModelA -> ModelB ->ModelC then
93 Django creates accessors like this:
94 - ModelA: modelb
95 - ModelB: modela_ptr, modelb, modelc
96 - ModelC: modela_ptr, modelb, modelb_ptr, modelc
97
98 These accessors allow Django (and everyone else) to travel up and down
99 the inheritance tree for the db object at hand. This is important for deletion among
100 other things.
101 """
102
103 def __new__(
104 cls, model_name: str, bases: tuple[type, ...], attrs: dict[str, Any], **kwargs: Any
105 ) -> type:
106 # skip special setup for PolymorphicModel itself
107 if attrs.pop("_meta_skip", False):
108 return super().__new__(cls, model_name, bases, attrs, **kwargs)
109
110 from .models import PolymorphicModel
111
112 new_class = cast(
113 type[PolymorphicModel], super().__new__(cls, model_name, bases, attrs, **kwargs)
114 )
115
116 # wrap on_delete handlers of reverse relations back to this model with the
117 # polymorphic deletion guard
118 for fk in new_class._meta.fields:
119 if isinstance(fk, (models.ForeignKey, models.OneToOneField)) and not isinstance(
120 fk.remote_field.on_delete, PolymorphicGuard
121 ):
122 fk.remote_field.on_delete = PolymorphicGuard(fk.remote_field.on_delete) # type: ignore[arg-type]
123
124 # replace the parent/child descriptors
125 if new_class._meta.parents and not (new_class._meta.abstract or new_class._meta.proxy):
126
127 def replace_inheritance_descriptors(model):
128 for super_cls, field_to_super in model._meta.parents.items():
129 if issubclass(super_cls, PolymorphicModel):
130 if field_to_super is not None:
131 setattr(
132 new_class,
133 field_to_super.name,
134 NonPolymorphicForwardOneToOneDescriptor(field_to_super),
135 )
136 setattr(
137 super_cls,
138 field_to_super.remote_field.related_name
139 or field_to_super.remote_field.name,
140 NonPolymorphicReverseOneToOneDescriptor(
141 field_to_super.remote_field
142 ),
143 )
144 else: # pragma: no cover
145 # proxy models have no field_to_super because the relations
146 # are to the parent model - the else here should never
147 # happen b/c we filter out proxy models above
148 pass
149 replace_inheritance_descriptors(super_cls)
150
151 replace_inheritance_descriptors(new_class)
152 _clear_utility_caches()
153 return new_class
154
155 @property
156 def base_objects(self) -> models.Manager[Any]:
157 warnings.warn(
158 "Using PolymorphicModel.base_objects is deprecated.\n"
159 f"Use {self.__class__.__name__}.objects.non_polymorphic() instead.",
160 DeprecationWarning,
161 stacklevel=2,
162 )
163 return self._base_objects
164
165 @property
166 def _base_objects(self) -> models.Manager[Any]:
167 # Create a manager so the API works as expected. Just don't register it
168 # anymore in the Model Meta, so it doesn't substitute our polymorphic
169 # manager as default manager for the third level of inheritance when
170 # that third level doesn't define a manager at all.
171 manager: models.Manager[Any] = models.Manager()
172 manager.name = "base_objects"
173 manager.model = self
174 return manager
175
176 @property
177 def _default_manager(cls) -> PolymorphicManager[Any]:
178 mgr: Any = super()._default_manager # type: ignore[misc]
179 if (
180 check_dump
181 and sys._getframe(1).f_globals.get("__name__")
182 == "django.core.management.commands.dumpdata"
183 ):
184 # The downcasting of polymorphic querysets breaks dumpdata because it
185 # expects to serialize multi-table models at each inheritance level.
186 # dumpdata uses Model._default_manager to retrieve the objects by default
187 # and uses Model._base_manager to retrieve objects if the --all flag is
188 # specified. We need to make both of these managers polymorphic to satisfy
189 # our contract that both Model.objects (_default_manager) is polymorphic and
190 # reverse relations Other.related (_base_manager) to our polymorphic models
191 # are also polymorphic.
192 #
193 # It would be best if load/dump data constructed its own managers like
194 # migrations do, but it doesn't. The only way to get around this is to
195 # detect when dumpdata is running and return the non-polymorphic manager in
196 # that case. We do this here by inspecting the call stack and checking if
197 # it came from the dumpdata command module. We use a CPython specific API
198 # sys._getframe to inspect the call stack because it is very fast
199 # (10s of nanoseconds) and disable the check if not on CPython
200 # conceding that dumpdata will just not work in that case. It is important
201 # that this check be fast because _default_manager is accessed very often.
202 # inspect.stack() builds the entire stack frame and a bunch of complicated
203 # datastructures - its use here should be avoided.
204 #
205 # Note that if you are stepping through this code in the debugger it will
206 # be looking at the wrong frame because a bunch of debugging frames will be
207 # on the top of the stack.
208 return cast(
209 PolymorphicManager[Any],
210 mgr.non_polymorphic() if isinstance(mgr, PolymorphicManager) else mgr,
211 )
212 return cast(PolymorphicManager[Any], mgr)
213
214 @property
215 def _base_manager(cls) -> PolymorphicManager[Any]:
216 mgr: Any = super()._base_manager # type: ignore[misc]
217 if (
218 check_dump
219 and sys._getframe(1).f_globals.get("__name__")
220 == "django.core.management.commands.dumpdata"
221 ):
222 # base manager is used when the --all flag is passed - see analogous comment
223 # for _default_manager
224 return cast(
225 PolymorphicManager[Any],
226 mgr.non_polymorphic() if isinstance(mgr, PolymorphicManager) else mgr,
227 )
228 return cast(PolymorphicManager[Any], mgr)