| 1 |
""" |
| 2 |
QuerySet for PolymorphicModel |
| 3 |
""" |
| 4 |
|
| 5 |
from __future__ import annotations |
| 6 |
|
| 7 |
import copy |
| 8 |
import heapq |
| 9 |
from collections import defaultdict |
| 10 |
from collections.abc import Collection, Iterable, Iterator, Sequence |
| 11 |
from typing import TYPE_CHECKING, Any, Generic, cast, overload |
| 12 |
|
| 13 |
from django.contrib.contenttypes.models import ContentType |
| 14 |
from django.core.exceptions import FieldDoesNotExist |
| 15 |
from django.db import connections, models |
| 16 |
from django.db.models import FilteredRelation, Q |
| 17 |
from django.db.models.expressions import Combinable |
| 18 |
from django.db.models.query import ModelIterable, QuerySet |
| 19 |
from typing_extensions import Self, TypeVar |
| 20 |
|
| 21 |
from .query_translate import ( |
| 22 |
translate_polymorphic_field_path, |
| 23 |
translate_polymorphic_filter_definitions_in_args, |
| 24 |
translate_polymorphic_filter_definitions_in_kwargs, |
| 25 |
translate_polymorphic_Q_object, |
| 26 |
) |
| 27 |
from .utils import concrete_descendants, route_to_ancestor |
| 28 |
|
| 29 |
if TYPE_CHECKING: |
| 30 |
from .models import PolymorphicModel # noqa: F401 |
| 31 |
|
| 32 |
_All = TypeVar("_All", bound="PolymorphicModel", covariant=True) |
| 33 |
_Base = TypeVar("_Base", bound="PolymorphicModel", default="PolymorphicModel", covariant=True) |
| 34 |
|
| 35 |
_A = TypeVar("_A", bound="PolymorphicModel") |
| 36 |
_B = TypeVar("_B", bound="PolymorphicModel") |
| 37 |
_C = TypeVar("_C", bound="PolymorphicModel") |
| 38 |
_D = TypeVar("_D", bound="PolymorphicModel") |
| 39 |
|
| 40 |
Polymorphic_QuerySet_objects_per_request: int = 2000 |
| 41 |
""" |
| 42 |
The maximum number of objects requested per db-request by the polymorphic |
| 43 |
queryset.iterator() implementation |
| 44 |
""" |
| 45 |
|
| 46 |
if TYPE_CHECKING: |
| 47 |
|
| 48 |
class BasePolymorphicModelIterable(ModelIterable[_All]): |
| 49 |
pass |
| 50 |
else: |
| 51 |
|
| 52 |
class BasePolymorphicModelIterable(ModelIterable): |
| 53 |
pass |
| 54 |
|
| 55 |
|
| 56 |
class _Inconsistent: |
| 57 |
""" |
| 58 |
A marker class indicating that there is a mismatch between the content type |
| 59 |
and the actual class of an object retrieved from the database. |
| 60 |
""" |
| 61 |
|
| 62 |
... |
| 63 |
|
| 64 |
|
| 65 |
class PolymorphicModelIterable(BasePolymorphicModelIterable, Generic[_All, _Base]): |
| 66 |
""" |
| 67 |
ModelIterable for PolymorphicModel |
| 68 |
|
| 69 |
Yields real instances if qs.polymorphic_disabled is False, |
| 70 |
otherwise acts like a regular ModelIterable. |
| 71 |
""" |
| 72 |
|
| 73 |
queryset: "PolymorphicQuerySet[_All, _Base]" |
| 74 |
|
| 75 |
def __iter__(self) -> Iterator[_All]: |
| 76 |
base_iter = super().__iter__() |
| 77 |
if self.queryset.polymorphic_disabled: |
| 78 |
return base_iter |
| 79 |
return self._polymorphic_iterator(base_iter) |
| 80 |
|
| 81 |
def _polymorphic_iterator(self, base_iter: Iterator[_All]) -> Iterator[_All]: |
| 82 |
""" |
| 83 |
Here we do the same as:: |
| 84 |
|
| 85 |
real_results = queryset._get_real_instances(list(base_iter)) |
| 86 |
for o in real_results: yield o |
| 87 |
|
| 88 |
but it requests the objects in chunks from the database, |
| 89 |
with QuerySet.iterator(chunk_size) per chunk |
| 90 |
""" |
| 91 |
|
| 92 |
# some databases have a limit on the number of query parameters, we must |
| 93 |
# respect this for generating get_real_instances queries because those |
| 94 |
# queries do a large WHERE IN clause with primary keys |
| 95 |
max_chunk = connections[self.queryset.db].features.max_query_params |
| 96 |
sql_chunk = self.chunk_size if self.chunked_fetch else None |
| 97 |
if max_chunk: |
| 98 |
sql_chunk = ( |
| 99 |
max_chunk |
| 100 |
if not self.chunked_fetch # chunk_size was not provided |
| 101 |
else min(max_chunk, self.chunk_size or max_chunk) |
| 102 |
) |
| 103 |
|
| 104 |
sql_chunk = sql_chunk or Polymorphic_QuerySet_objects_per_request |
| 105 |
|
| 106 |
while True: |
| 107 |
base_result_objects = [] |
| 108 |
reached_end = False |
| 109 |
|
| 110 |
# Fetch in chunks |
| 111 |
for _ in range(sql_chunk): |
| 112 |
try: |
| 113 |
o = next(base_iter) |
| 114 |
base_result_objects.append(o) |
| 115 |
except StopIteration: |
| 116 |
reached_end = True |
| 117 |
break |
| 118 |
|
| 119 |
yield from self.queryset._get_real_instances(base_result_objects) |
| 120 |
|
| 121 |
if reached_end: |
| 122 |
return |
| 123 |
|
| 124 |
|
| 125 |
def transmogrify(cls: type[_All], obj: models.Model) -> _All: |
| 126 |
""" |
| 127 |
Upcast a class to a different type without asking questions. |
| 128 |
""" |
| 129 |
if "__init__" not in obj.__class__.__dict__: |
| 130 |
# Just assign __class__ to a different value. |
| 131 |
new = obj |
| 132 |
new.__class__ = cls |
| 133 |
return cast(_All, new) |
| 134 |
else: |
| 135 |
# Run constructor, reassign values |
| 136 |
new = cls() |
| 137 |
for k, v in obj.__dict__.items(): |
| 138 |
new.__dict__[k] = v # pyright: ignore[reportIndexIssue] |
| 139 |
return new |
| 140 |
|
| 141 |
|
| 142 |
################################################################################### |
| 143 |
# PolymorphicQuerySet |
| 144 |
|
| 145 |
|
| 146 |
class PolymorphicQuerySet(QuerySet[_All], Generic[_All, _Base]): |
| 147 |
""" |
| 148 |
QuerySet for PolymorphicModel |
| 149 |
|
| 150 |
Contains the core functionality for PolymorphicModel |
| 151 |
|
| 152 |
Usually not explicitly needed, except if a custom queryset class |
| 153 |
is to be used. |
| 154 |
""" |
| 155 |
|
| 156 |
polymorphic_disabled: bool |
| 157 |
polymorphic_deferred_loading: tuple[set[str], bool] |
| 158 |
|
| 159 |
def __init__(self, *args: Any, **kwargs: Any) -> None: |
| 160 |
super().__init__(*args, **kwargs) |
| 161 |
self._iterable_class = PolymorphicModelIterable |
| 162 |
|
| 163 |
self.polymorphic_disabled = False |
| 164 |
# A parallel structure to django.db.models.query.Query.deferred_loading, |
| 165 |
# which we maintain with the untranslated field names passed to |
| 166 |
# .defer() and .only() in order to be able to retranslate them when |
| 167 |
# retrieving the real instance (so that the deferred fields apply |
| 168 |
# to that queryset as well). |
| 169 |
self.polymorphic_deferred_loading = (set(), True) |
| 170 |
|
| 171 |
def _clone(self, *args: Any, **kwargs: Any) -> Self: |
| 172 |
# Django's _clone only copies its own variables, so we need to copy ours here |
| 173 |
new = cast(Self, super()._clone(*args, **kwargs)) # type: ignore[misc] |
| 174 |
new.polymorphic_disabled = self.polymorphic_disabled |
| 175 |
new.polymorphic_deferred_loading = ( |
| 176 |
copy.copy(self.polymorphic_deferred_loading[0]), |
| 177 |
self.polymorphic_deferred_loading[1], |
| 178 |
) |
| 179 |
return new |
| 180 |
|
| 181 |
@classmethod |
| 182 |
def as_manager(cls) -> models.Manager[_All]: |
| 183 |
""" |
| 184 |
Override base :meth:`~django.db.models.query.QuerySet.as_manager` to return |
| 185 |
a manager extended from :class:`polymorphic.managers.PolymorphicManager`. |
| 186 |
""" |
| 187 |
|
| 188 |
from .managers import PolymorphicManager |
| 189 |
|
| 190 |
manager = PolymorphicManager[_All, _Base].from_queryset(cls)() |
| 191 |
setattr(manager, "_built_with_as_manager", True) |
| 192 |
return manager |
| 193 |
|
| 194 |
as_manager.queryset_only = True # type: ignore[attr-defined] |
| 195 |
|
| 196 |
def bulk_create( |
| 197 |
self, |
| 198 |
objs: Iterable[_All], |
| 199 |
batch_size: int | None = None, |
| 200 |
ignore_conflicts: bool = False, |
| 201 |
update_conflicts: bool = False, |
| 202 |
update_fields: Collection[str] | None = None, |
| 203 |
unique_fields: Collection[str] | None = None, |
| 204 |
) -> list[_All]: |
| 205 |
objs = list(objs) |
| 206 |
for obj in objs: |
| 207 |
obj.pre_save_polymorphic() |
| 208 |
return super().bulk_create(objs, batch_size, ignore_conflicts=ignore_conflicts) |
| 209 |
|
| 210 |
def non_polymorphic(self) -> PolymorphicQuerySet[_Base, _Base]: |
| 211 |
"""switch off polymorphic behaviour for this query. |
| 212 |
When the queryset is evaluated, only objects of the type of the |
| 213 |
base class used for this query are returned.""" |
| 214 |
qs = self._clone() |
| 215 |
qs.polymorphic_disabled = True |
| 216 |
if issubclass(qs._iterable_class, PolymorphicModelIterable): |
| 217 |
qs._iterable_class = ModelIterable |
| 218 |
return cast(PolymorphicQuerySet[_Base, _Base], qs) |
| 219 |
|
| 220 |
@overload |
| 221 |
def instance_of(self, __a: type[_A], /) -> PolymorphicQuerySet[_A, _Base]: ... |
| 222 |
|
| 223 |
@overload |
| 224 |
def instance_of( |
| 225 |
self, __a: type[_A], __b: type[_B], / |
| 226 |
) -> PolymorphicQuerySet[_A | _B, _Base]: ... |
| 227 |
|
| 228 |
@overload |
| 229 |
def instance_of( |
| 230 |
self, __a: type[_A], __b: type[_B], __c: type[_C], / |
| 231 |
) -> PolymorphicQuerySet[_A | _B | _C, _Base]: ... |
| 232 |
|
| 233 |
@overload |
| 234 |
def instance_of( |
| 235 |
self, __a: type[_A], __b: type[_B], __c: type[_C], __d: type[_D], / |
| 236 |
) -> PolymorphicQuerySet[_A | _B | _C | _D, _Base]: ... |
| 237 |
|
| 238 |
@overload |
| 239 |
def instance_of(self, *args: type["PolymorphicModel"]) -> PolymorphicQuerySet[_All, _Base]: ... |
| 240 |
|
| 241 |
def instance_of( |
| 242 |
self, *args: type["PolymorphicModel"] |
| 243 |
) -> PolymorphicQuerySet["PolymorphicModel", _Base]: |
| 244 |
"""Filter the queryset to only include the classes in args (and their subclasses).""" |
| 245 |
# Implementation in _translate_polymorphic_filter_defnition. |
| 246 |
return self.filter(instance_of=args) |
| 247 |
|
| 248 |
def not_instance_of(self, *args: type["PolymorphicModel"]) -> Self: |
| 249 |
"""Filter the queryset to exclude the classes in args (and their subclasses).""" |
| 250 |
# Implementation in _translate_polymorphic_filter_defnition.""" |
| 251 |
return self.filter(not_instance_of=args) |
| 252 |
|
| 253 |
def _filter_or_exclude(self, negate: bool, args: Any, kwargs: Any) -> Self: |
| 254 |
# We override this internal Django function as it is used for all filter member functions. |
| 255 |
q_objects = translate_polymorphic_filter_definitions_in_args( |
| 256 |
queryset_model=self.model, args=args, using=self.db |
| 257 |
) |
| 258 |
# filter_field='data' |
| 259 |
additional_args = translate_polymorphic_filter_definitions_in_kwargs( |
| 260 |
queryset_model=self.model, kwargs=kwargs, using=self.db |
| 261 |
) |
| 262 |
args = list(q_objects) + additional_args |
| 263 |
return cast(Self, super()._filter_or_exclude(negate=negate, args=args, kwargs=kwargs)) # type: ignore[misc] |
| 264 |
|
| 265 |
def order_by(self, *field_names: str | Combinable) -> Self: |
| 266 |
"""translate the field paths in the args, then call vanilla order_by.""" |
| 267 |
translated_fields = [ |
| 268 |
translate_polymorphic_field_path(self.model, a) |
| 269 |
if isinstance(a, str) |
| 270 |
else a # allow expressions to pass unchanged |
| 271 |
for a in field_names |
| 272 |
] |
| 273 |
return super().order_by(*translated_fields) |
| 274 |
|
| 275 |
@overload |
| 276 |
def defer(self, field: None, /) -> Self: ... |
| 277 |
@overload |
| 278 |
def defer(self, *fields: str) -> Self: ... |
| 279 |
def defer(self, *fields: str | None) -> Self: |
| 280 |
""" |
| 281 |
Translate the field paths in the args, then call vanilla defer. |
| 282 |
|
| 283 |
Also retain a copy of the original fields passed, which we'll need |
| 284 |
when we're retrieving the real instance (since we'll need to translate |
| 285 |
them again, as the model will have changed). |
| 286 |
""" |
| 287 |
# Filter out None and translate fields |
| 288 |
str_fields = tuple(f for f in fields if f is not None) |
| 289 |
if str_fields: |
| 290 |
new_fields = tuple(translate_polymorphic_field_path(self.model, a) for a in str_fields) |
| 291 |
clone = super().defer(*new_fields) |
| 292 |
clone._polymorphic_add_deferred_loading(str_fields) |
| 293 |
else: |
| 294 |
# Handle defer(None) case |
| 295 |
clone = super().defer(None) |
| 296 |
return clone |
| 297 |
|
| 298 |
def only(self, *fields: str) -> Self: |
| 299 |
""" |
| 300 |
Translate the field paths in the args, then call vanilla only. |
| 301 |
|
| 302 |
Also retain a copy of the original fields passed, which we'll need |
| 303 |
when we're retrieving the real instance (since we'll need to translate |
| 304 |
them again, as the model will have changed). |
| 305 |
""" |
| 306 |
new_fields = {translate_polymorphic_field_path(self.model, a) for a in fields} |
| 307 |
clone = super().only(*new_fields) |
| 308 |
only_fields, deferred = clone.query.deferred_loading |
| 309 |
if only_fields and not deferred: |
| 310 |
clone.query.deferred_loading = (only_fields | {"polymorphic_ctype_id"}, False) |
| 311 |
clone._polymorphic_add_immediate_loading(fields) |
| 312 |
return clone |
| 313 |
|
| 314 |
def _polymorphic_add_deferred_loading(self, field_names: Iterable[str]) -> None: |
| 315 |
""" |
| 316 |
Follows the logic of django.db.models.query.Query.add_deferred_loading(), |
| 317 |
but for the non-translated field names that were passed to self.defer(). |
| 318 |
""" |
| 319 |
existing, defer = self.polymorphic_deferred_loading |
| 320 |
if defer: |
| 321 |
# Add to existing deferred names. |
| 322 |
self.polymorphic_deferred_loading = existing.union(field_names), True |
| 323 |
else: |
| 324 |
# Remove names from the set of any existing "immediate load" names. |
| 325 |
self.polymorphic_deferred_loading = existing.difference(field_names), False |
| 326 |
|
| 327 |
def _polymorphic_add_immediate_loading(self, field_names: Iterable[str]) -> None: |
| 328 |
""" |
| 329 |
Follows the logic of django.db.models.query.Query.add_immediate_loading(), |
| 330 |
but for the non-translated field names that were passed to self.only() |
| 331 |
""" |
| 332 |
existing, defer = self.polymorphic_deferred_loading |
| 333 |
field_names = set(field_names) |
| 334 |
if "pk" in field_names: |
| 335 |
field_names.remove("pk") |
| 336 |
field_names.add(self.model._meta.pk.name) |
| 337 |
|
| 338 |
if defer: |
| 339 |
# Remove any existing deferred names from the current set before |
| 340 |
# setting the new names. |
| 341 |
self.polymorphic_deferred_loading = field_names.difference(existing), False |
| 342 |
else: |
| 343 |
# Replace any existing "immediate load" field names. |
| 344 |
self.polymorphic_deferred_loading = field_names, False |
| 345 |
|
| 346 |
def _process_aggregate_args(self, args: Sequence[Any], kwargs: dict[str, Any]) -> None: |
| 347 |
"""for aggregate and annotate kwargs: allow ModelX___field syntax for kwargs, forbid it for args. |
| 348 |
Modifies kwargs if needed (these are Aggregate objects, we translate the lookup member variable) |
| 349 |
""" |
| 350 |
___lookup_assert_msg = "PolymorphicModel: annotate()/aggregate(): ___ model lookup supported for keyword arguments only" |
| 351 |
|
| 352 |
def patch_lookup(a): |
| 353 |
# The field on which the aggregate operates is |
| 354 |
# stored inside a complex query expression. |
| 355 |
if isinstance(a, Q): |
| 356 |
# modify in place - this should be fixed if we want immutable |
| 357 |
# aggregate/annotation expressions |
| 358 |
a.children = translate_polymorphic_Q_object(self.model, a).children |
| 359 |
elif isinstance(a, FilteredRelation): |
| 360 |
patch_lookup(a.condition) |
| 361 |
elif isinstance(a, models.F): |
| 362 |
a.name = translate_polymorphic_field_path(self.model, a.name) # type: ignore[attr-defined] |
| 363 |
elif hasattr(a, "get_source_expressions"): |
| 364 |
for source_expression in a.get_source_expressions(): |
| 365 |
if source_expression is not None: |
| 366 |
patch_lookup(source_expression) |
| 367 |
else: |
| 368 |
a.name = translate_polymorphic_field_path(self.model, a.name) |
| 369 |
|
| 370 |
def test___lookup(a): |
| 371 |
"""*args might be complex expressions too in django 1.8 so |
| 372 |
the testing for a '___' is rather complex on this one""" |
| 373 |
if isinstance(a, Q): |
| 374 |
|
| 375 |
def tree_node_test___lookup(my_model, node): |
| 376 |
"process all children of this Q node" |
| 377 |
for i in range(len(node.children)): |
| 378 |
child = node.children[i] |
| 379 |
|
| 380 |
if type(child) is tuple: |
| 381 |
# this Q object child is a tuple => a kwarg like Q( instance_of=ModelB ) |
| 382 |
assert "___" not in child[0], ___lookup_assert_msg |
| 383 |
else: |
| 384 |
# this Q object child is another Q object, recursively process this as well |
| 385 |
tree_node_test___lookup(my_model, child) |
| 386 |
|
| 387 |
tree_node_test___lookup(self.model, a) |
| 388 |
elif hasattr(a, "get_source_expressions"): |
| 389 |
for source_expression in a.get_source_expressions(): |
| 390 |
if source_expression is not None: |
| 391 |
test___lookup(source_expression) |
| •392 |
elif a is not None: |
| 393 |
assert "___" not in a.name, ___lookup_assert_msg |
| 394 |
|
| 395 |
for a in args: |
| 396 |
test___lookup(a) |
| 397 |
for a in kwargs.values(): |
| 398 |
patch_lookup(a) |
| 399 |
|
| 400 |
def annotate(self, *args: Any, **kwargs: Any) -> Self: |
| 401 |
"""translate the polymorphic field paths in the kwargs, then call vanilla annotate. |
| 402 |
_get_real_instances will do the rest of the job after executing the query.""" |
| 403 |
self._process_aggregate_args(args, kwargs) |
| 404 |
return super().annotate(*args, **kwargs) |
| 405 |
|
| 406 |
def aggregate(self, *args: Any, **kwargs: Any) -> dict[str, Any]: |
| 407 |
"""translate the polymorphic field paths in the kwargs, then call vanilla aggregate. |
| 408 |
We need no polymorphic object retrieval for aggregate => switch it off.""" |
| 409 |
self._process_aggregate_args(args, kwargs) |
| 410 |
qs = self.non_polymorphic() |
| 411 |
return super(PolymorphicQuerySet, qs).aggregate(*args, **kwargs) |
| 412 |
|
| 413 |
# Starting with Django 1.9, the copy returned by 'qs.values(...)' has the |
| 414 |
# same class as 'qs', so our polymorphic modifications would apply. |
| 415 |
# We want to leave values queries untouched, so we set 'polymorphic_disabled'. |
| 416 |
def _values(self, *args: Any, **kwargs: Any) -> Self: |
| 417 |
clone = cast(Self, super()._values(*args, **kwargs)) # type: ignore[misc] |
| 418 |
clone.polymorphic_disabled = True |
| 419 |
return clone |
| 420 |
|
| 421 |
# Since django_polymorphic 'V1.0 beta2', extra() always returns polymorphic results. |
| 422 |
# The resulting objects are required to have a unique primary key within the result set |
| 423 |
# (otherwise an error is thrown). |
| 424 |
# The "polymorphic" keyword argument is not supported anymore. |
| 425 |
# def extra(self, *args, **kwargs): |
| 426 |
|
| 427 |
def _get_real_instances(self, base_result_objects: Sequence[_All]) -> list[_All]: |
| 428 |
""" |
| 429 |
Polymorphic object loader |
| 430 |
|
| 431 |
Does the same as: |
| 432 |
|
| 433 |
return [ o.get_real_instance() for o in base_result_objects ] |
| 434 |
|
| 435 |
but more efficiently. |
| 436 |
|
| 437 |
The list base_result_objects contains the objects from the executed |
| 438 |
base class query. The class of all of them is self.model (our base model). |
| 439 |
|
| 440 |
Some, many or all of these objects were not created and stored as |
| 441 |
class self.model, but as a class derived from self.model. We want to re-fetch |
| 442 |
these objects from the db as their original class so we can return them |
| 443 |
just as they were created/saved. |
| 444 |
|
| 445 |
We identify these objects by looking at o.polymorphic_ctype, which specifies |
| 446 |
the real class of these objects (the class at the time they were saved). |
| 447 |
|
| 448 |
First, we sort the result objects in base_result_objects for their |
| 449 |
subclass (from o.polymorphic_ctype), and then we execute one db query per |
| 450 |
subclass of objects. Here, we handle any annotations from annotate(). |
| 451 |
|
| 452 |
Finally we re-sort the resulting objects into the correct order and |
| 453 |
return them as a list. |
| 454 |
""" |
| 455 |
resultlist: list[Any] = [] # polymorphic list of result-objects |
| 456 |
|
| 457 |
# dict contains one entry per unique model type occurring in result, |
| 458 |
# in the format idlist_per_model[modelclass]=[list-of-object-ids] |
| 459 |
idlist_per_model: defaultdict[Any, list[Any]] = defaultdict(list) |
| 460 |
indexlist_per_model: defaultdict[Any, list[tuple[int, int]]] = defaultdict(list) |
| 461 |
|
| 462 |
# priority queue holding the query order of concrete classes |
| 463 |
# we need this so we can retry fetching objects further up the hierarchy with |
| 464 |
# stale content types - this can happen in some legitimate cases (deletion) |
| 465 |
# we build up and pop classes off this queue to ensure we process in tree |
| 466 |
# traversal order (leaves first) - this allows us to retry fetching as parent |
| 467 |
# classes if child class retrieval fails |
| 468 |
classes_to_query: list[tuple[int, Any]] = [] |
| 469 |
|
| 470 |
# use the pk attribute for the base model type used in the query to identify |
| 471 |
# objects |
| 472 |
pk_name = self.model._meta.pk.attname |
| 473 |
|
| 474 |
# - sort base_result_object ids into idlist_per_model lists, depending on their real class; |
| 475 |
# - store objects that already have the correct class into "results" |
| 476 |
content_type_manager = ContentType.objects.db_manager(self.db) |
| 477 |
self_model_class_id = content_type_manager.get_for_model( |
| 478 |
self.model, for_concrete_model=False |
| 479 |
).pk |
| 480 |
self_concrete_model_class_id = content_type_manager.get_for_model( |
| 481 |
self.model, for_concrete_model=True |
| 482 |
).pk |
| 483 |
|
| 484 |
class_priorities = { |
| 485 |
mdl: idx + 1 |
| 486 |
for idx, mdl in enumerate((*reversed(concrete_descendants(self.model)), self.model)) |
| 487 |
} |
| 488 |
|
| 489 |
for i, base_object in enumerate(base_result_objects): |
| 490 |
if base_object.polymorphic_ctype_id == self_model_class_id: |
| 491 |
# Real class is exactly the same as base class, go straight to results |
| 492 |
resultlist.append(base_object) |
| 493 |
else: |
| 494 |
real_concrete_class = base_object.get_real_instance_class() |
| 495 |
real_concrete_class_id = base_object.get_real_concrete_instance_class_id() |
| 496 |
|
| 497 |
if real_concrete_class_id is None: |
| 498 |
# Dealing with a stale content type |
| 499 |
continue |
| 500 |
elif real_concrete_class_id == self_concrete_model_class_id: |
| 501 |
# Real and base classes share the same concrete ancestor, |
| 502 |
# upcast it and put it in the results |
| 503 |
# real_concrete_class is guaranteed to be a PolymorphicModel subclass |
| 504 |
resultlist.append( |
| 505 |
transmogrify( |
| 506 |
cast("type[PolymorphicModel]", real_concrete_class), base_object |
| 507 |
) |
| 508 |
) |
| 509 |
else: |
| 510 |
# This model has a concrete derived class, track it for bulk retrieval. |
| 511 |
real_concrete_class = cast( |
| 512 |
"type[_All] | None", |
| 513 |
content_type_manager.get_for_id(real_concrete_class_id).model_class(), |
| 514 |
) |
| 515 |
if real_concrete_class is not None: |
| 516 |
if real_concrete_class not in idlist_per_model: |
| 517 |
# Maintain a priority queue to process the model classes |
| 518 |
# in order of their occurrence in the inheritance tree - leafs |
| 519 |
# first |
| 520 |
heapq.heappush( |
| 521 |
classes_to_query, |
| 522 |
( |
| 523 |
class_priorities.get(real_concrete_class, 0), |
| 524 |
real_concrete_class, |
| 525 |
), |
| 526 |
) |
| 527 |
idlist_per_model[real_concrete_class].append(getattr(base_object, pk_name)) |
| 528 |
indexlist_per_model[real_concrete_class].append((i, len(resultlist))) |
| 529 |
resultlist.append(None) |
| 530 |
|
| 531 |
# For each model in "idlist_per_model" request its objects (the real model) |
| 532 |
# from the db and store them in results[]. |
| 533 |
# Then we copy the annotate fields from the base objects to the real objects. |
| 534 |
# Then we copy the extra() select fields from the base objects to the real objects. |
| 535 |
# TODO: defer(), only(): support for these would be around here |
| 536 |
|
| 537 |
while classes_to_query: |
| 538 |
_, real_concrete_class = heapq.heappop(classes_to_query) |
| 539 |
assert real_concrete_class is not None # Ensured by guard at line 467 |
| 540 |
idlist = idlist_per_model.pop(real_concrete_class) |
| 541 |
indices = indexlist_per_model.pop(real_concrete_class) |
| 542 |
real_objects = real_concrete_class._base_objects.db_manager(self.db).filter( |
| 543 |
**{(f"{pk_name}__in"): idlist} |
| 544 |
) |
| 545 |
# copy select related configuration to new qs |
| 546 |
real_objects.query.select_related = self.query.select_related |
| 547 |
|
| 548 |
# Copy deferred fields configuration to the new queryset |
| 549 |
deferred_loading_fields = [] |
| 550 |
existing_fields = self.polymorphic_deferred_loading[0] |
| 551 |
for field in existing_fields: |
| 552 |
try: |
| 553 |
translated_field_name = translate_polymorphic_field_path( |
| 554 |
real_concrete_class, field |
| 555 |
) |
| 556 |
except AssertionError: |
| 557 |
if "___" in field: |
| 558 |
# The originally passed argument to .defer() or .only() |
| 559 |
# was in the form Model2B___field2, where Model2B is |
| 560 |
# now a superclass of real_concrete_class. Thus it's |
| 561 |
# sufficient to just use the field name. |
| 562 |
translated_field_name = field.rpartition("___")[-1] |
| 563 |
|
| 564 |
# Check if the field does exist. |
| 565 |
# Ignore deferred fields that don't exist in this subclass type. |
| 566 |
try: |
| 567 |
real_concrete_class._meta.get_field(translated_field_name) |
| 568 |
except FieldDoesNotExist: |
| 569 |
continue |
| 570 |
else: |
| 571 |
raise |
| 572 |
|
| 573 |
deferred_loading_fields.append(translated_field_name) |
| 574 |
real_objects.query.deferred_loading = ( |
| 575 |
set(deferred_loading_fields), |
| 576 |
self.query.deferred_loading[1], |
| 577 |
) |
| 578 |
|
| 579 |
real_objects_dict = { |
| 580 |
getattr(real_object, pk_name): real_object for real_object in real_objects |
| 581 |
} |
| 582 |
|
| 583 |
for base_idx, result_idx in indices: |
| 584 |
base_object = base_result_objects[base_idx] |
| 585 |
o_pk = getattr(base_object, pk_name) |
| 586 |
real_object = real_objects_dict.get(o_pk) |
| 587 |
if real_object is None: |
| 588 |
# Our content type is pointing to a row that does not exist anymore |
| 589 |
# We try to find the next best available parent row |
| 590 |
inheritance_path = route_to_ancestor(real_concrete_class, self.model) |
| 591 |
if not inheritance_path or inheritance_path[0].model is self.model: |
| 592 |
resultlist[result_idx] = base_object |
| 593 |
else: |
| 594 |
next_best_class = inheritance_path[0].model |
| 595 |
if next_best_class not in idlist_per_model: |
| 596 |
# add this class to the priority try queue |
| 597 |
heapq.heappush( |
| 598 |
classes_to_query, |
| 599 |
(class_priorities.get(next_best_class, 0), next_best_class), |
| 600 |
) |
| 601 |
idlist_per_model[next_best_class].append(o_pk) |
| 602 |
indexlist_per_model[next_best_class].append((base_idx, result_idx)) |
| 603 |
resultlist[result_idx] = _Inconsistent |
| 604 |
continue |
| 605 |
|
| 606 |
# need shallow copy to avoid duplication in caches (see PR #353) |
| 607 |
real_object = copy.copy(real_object) |
| 608 |
real_class = ( |
| 609 |
real_concrete_class |
| 610 |
if resultlist[result_idx] is _Inconsistent |
| 611 |
else real_object.get_real_instance_class() |
| 612 |
) |
| 613 |
|
| 614 |
# If the real class is a proxy, upcast it |
| 615 |
if real_class != real_concrete_class: |
| 616 |
real_object = transmogrify( |
| 617 |
cast("type[PolymorphicModel]", real_class), real_object |
| 618 |
) |
| 619 |
|
| 620 |
if self.query.annotations: |
| 621 |
# New in Django 3.2+: annotation_select contains only the selected annotations |
| 622 |
# (excluding aliases). Fallback for older Django versions if needed. |
| 623 |
annotation_select = getattr( |
| 624 |
self.query, "annotation_select", self.query.annotations |
| 625 |
) |
| 626 |
for anno_field_name in annotation_select.keys(): |
| 627 |
if hasattr(base_object, anno_field_name): |
| 628 |
attr = getattr(base_object, anno_field_name) |
| 629 |
setattr(real_object, anno_field_name, attr) |
| 630 |
|
| 631 |
if self.query.extra_select: |
| 632 |
for select_field_name in self.query.extra_select.keys(): |
| 633 |
attr = getattr(base_object, select_field_name) |
| 634 |
setattr(real_object, select_field_name, attr) |
| 635 |
|
| 636 |
resultlist[result_idx] = real_object |
| 637 |
|
| 638 |
resultlist = [i for i in resultlist if i and i is not _Inconsistent] |
| 639 |
|
| 640 |
# set polymorphic_annotate_names in all objects (currently just used for debugging/printing) |
| 641 |
if self.query.annotations: |
| 642 |
# get annotate field list |
| 643 |
annotation_select = getattr(self.query, "annotation_select", self.query.annotations) |
| 644 |
annotate_names = list(annotation_select.keys()) |
| 645 |
for real_object in resultlist: |
| 646 |
real_object.polymorphic_annotate_names = annotate_names |
| 647 |
|
| 648 |
# set polymorphic_extra_select_names in all objects (currently just used for debugging/printing) |
| 649 |
if self.query.extra_select: |
| 650 |
# get extra select field list |
| 651 |
extra_select_names = list(self.query.extra_select.keys()) |
| 652 |
for real_object in resultlist: |
| 653 |
real_object.polymorphic_extra_select_names = extra_select_names |
| 654 |
|
| 655 |
return resultlist |
| 656 |
|
| 657 |
def __repr__(self, *args, **kwargs): |
| 658 |
if self.model.polymorphic_query_multiline_output: |
| 659 |
result = ",\n ".join(repr(o) for o in self.all()) |
| 660 |
return f"[ {result} ]" |
| 661 |
else: |
| 662 |
return super().__repr__(*args, **kwargs) |
| 663 |
|
| 664 |
class _p_list_class(list[Any]): |
| 665 |
def __repr__(self, *args: Any, **kwargs: Any) -> str: |
| 666 |
result = ",\n ".join(repr(o) for o in self) |
| 667 |
return f"[ {result} ]" |
| 668 |
|
| 669 |
def get_real_instances(self, base_result_objects: Iterable[_All] | None = None) -> list[_All]: |
| 670 |
""" |
| 671 |
Cast a list of objects to their actual classes. |
| 672 |
|
| 673 |
This does roughly the same as:: |
| 674 |
|
| 675 |
return [ o.get_real_instance() for o in base_result_objects ] |
| 676 |
|
| 677 |
but more efficiently. |
| 678 |
|
| 679 |
:rtype: PolymorphicQuerySet |
| 680 |
""" |
| 681 |
"same as _get_real_instances, but make sure that __repr__ for ShowField... creates correct output" |
| 682 |
if base_result_objects is None: |
| 683 |
base_result_objects = cast(Iterable[_All], self) |
| 684 |
# Convert to list if needed for indexing |
| 685 |
base_result_list: Sequence[_All] |
| 686 |
if not isinstance(base_result_objects, list): |
| 687 |
base_result_list = list(base_result_objects) |
| 688 |
else: |
| 689 |
base_result_list = base_result_objects |
| 690 |
olist = self._get_real_instances(base_result_list) |
| 691 |
if not self.model.polymorphic_query_multiline_output: |
| 692 |
return olist |
| 693 |
clist = PolymorphicQuerySet._p_list_class(olist) |
| 694 |
return clist |
| 695 |
|
| 696 |
def delete(self) -> tuple[int, dict[str, int]]: |
| 697 |
""" |
| 698 |
Deletion will be done non-polymorphically because Django's multi-table deletion |
| 699 |
mechanism is already walking the class hierarchy and producing a correct |
| 700 |
deletion graph. Introducing polymorphic querysets into the deletion process |
| 701 |
disrupts the model hierarchy/relationship traversal. |
| 702 |
""" |
| 703 |
return QuerySet.delete(self.non_polymorphic()) |