| 1 |
from typing import Any, cast |
| 2 |
|
| 3 |
from django.db.models import QuerySet |
| 4 |
from django.db.models.fields.related_descriptors import ( |
| 5 |
ForwardOneToOneDescriptor, |
| 6 |
ReverseOneToOneDescriptor, |
| 7 |
) |
| 8 |
|
| 9 |
|
| 10 |
class NonPolymorphicForwardOneToOneDescriptor(ForwardOneToOneDescriptor): |
| 11 |
""" |
| 12 |
A custom descriptor for forward OneToOne relations to polymorphic models that |
| 13 |
returns non-polymorphic instances. This is used for the parent to child links |
| 14 |
in multi-table polymorphic models. |
| 15 |
""" |
| 16 |
|
| 17 |
def get_queryset(self, **hints: Any) -> QuerySet[Any]: |
| 18 |
return cast( |
| 19 |
QuerySet[Any], |
| 20 |
( |
| 21 |
getattr( |
| 22 |
self.field.remote_field.model, |
| 23 |
"_base_objects", |
| 24 |
# don't fail if we've been used on a non-poly model |
| 25 |
self.field.remote_field.model._base_manager, |
| 26 |
) |
| 27 |
) |
| 28 |
.db_manager(hints=hints) |
| 29 |
.all(), |
| 30 |
) |
| 31 |
|
| 32 |
|
| 33 |
class NonPolymorphicReverseOneToOneDescriptor(ReverseOneToOneDescriptor): |
| 34 |
""" |
| 35 |
A custom descriptor for reverse OneToOne relations to polymorphic models that |
| 36 |
returns non-polymorphic instances. This is used for the child to parent links |
| 37 |
in multi-table polymorphic models. |
| 38 |
""" |
| 39 |
|
| 40 |
def get_queryset(self, **hints: Any) -> QuerySet[Any]: |
| 41 |
return cast( |
| 42 |
QuerySet[Any], |
| 43 |
( |
| 44 |
getattr( |
| 45 |
self.related.related_model, |
| 46 |
"_base_objects", |
| 47 |
# don't fail if we've been used on a non-poly model |
| 48 |
self.related.related_model._base_manager, |
| 49 |
) |
| 50 |
) |
| 51 |
.db_manager(hints=hints) |
| 52 |
.all(), |
| 53 |
) |