| 1 |
""" |
| 2 |
PolymorphicQuerySet support functions |
| 3 |
""" |
| 4 |
|
| 5 |
import copy |
| 6 |
from functools import reduce |
| 7 |
from operator import or_ |
| 8 |
from typing import Any |
| 9 |
|
| 10 |
from django.apps import apps |
| 11 |
from django.contrib.contenttypes.models import ContentType |
| 12 |
from django.core.exceptions import FieldDoesNotExist, FieldError |
| 13 |
from django.db import models |
| 14 |
from django.db.models import Q, Subquery |
| 15 |
from django.db.models.fields.related import ForeignObjectRel, RelatedField |
| 16 |
from django.db.utils import DEFAULT_DB_ALIAS |
| 17 |
|
| 18 |
from .utils import _lazy_ctype, _map_queryname_to_class, concrete_descendants |
| 19 |
|
| 20 |
# These functions implement the additional filter- and Q-object functionality. |
| 21 |
# They form a kind of small framework for easily adding more |
| 22 |
# functionality to filters and Q objects. |
| 23 |
# Probably a more general queryset enhancement class could be made out of them. |
| 24 |
|
| 25 |
################################################################################### |
| 26 |
# PolymorphicQuerySet support functions |
| 27 |
|
| 28 |
|
| 29 |
def translate_polymorphic_filter_definitions_in_kwargs( |
| 30 |
queryset_model: type[models.Model], kwargs: dict[str, Any], using: str = DEFAULT_DB_ALIAS |
| 31 |
) -> list[Q]: |
| 32 |
""" |
| 33 |
Translate the keyword argument list for PolymorphicQuerySet.filter() |
| 34 |
|
| 35 |
Any kwargs with special polymorphic functionality are replaced in the kwargs |
| 36 |
dict with their vanilla django equivalents. |
| 37 |
|
| 38 |
For some kwargs a direct replacement is not possible, as a Q object is needed |
| 39 |
instead to implement the required functionality. In these cases the kwarg is |
| 40 |
deleted from the kwargs dict and a Q object is added to the return list. |
| 41 |
|
| 42 |
Modifies: kwargs dict |
| 43 |
Returns: a list of non-keyword-arguments (Q objects) to be added to the filter() query. |
| 44 |
""" |
| 45 |
additional_args = [] |
| 46 |
for field_path, val in kwargs.copy().items(): # `copy` so we're not mutating the dict |
| 47 |
new_expr = _translate_polymorphic_filter_definition( |
| 48 |
queryset_model, field_path, val, using=using |
| 49 |
) |
| 50 |
|
| 51 |
if isinstance(new_expr, tuple): |
| 52 |
# replace kwargs element |
| 53 |
del kwargs[field_path] |
| 54 |
kwargs[new_expr[0]] = new_expr[1] |
| 55 |
|
| 56 |
elif isinstance(new_expr, models.Q): |
| 57 |
del kwargs[field_path] |
| 58 |
additional_args.append(new_expr) |
| 59 |
|
| 60 |
return additional_args |
| 61 |
|
| 62 |
|
| 63 |
def translate_polymorphic_Q_object( |
| 64 |
queryset_model: type[models.Model], potential_q_object: Q, using: str = DEFAULT_DB_ALIAS |
| 65 |
) -> Q: |
| 66 |
def tree_node_correct_field_specs(my_model: type[models.Model], node: Q) -> Q: |
| 67 |
"process all children of this Q node" |
| 68 |
cpy = copy.copy(node) |
| 69 |
cpy.children = [] |
| 70 |
for child in node.children: |
| 71 |
if isinstance(child, (tuple, list)): |
| 72 |
# this Q object child is a tuple => a kwarg like Q( instance_of=ModelB ) |
| 73 |
key, val = child |
| 74 |
new_expr = _translate_polymorphic_filter_definition( |
| 75 |
my_model, key, val, using=using |
| 76 |
) |
| 77 |
cpy.children.append(new_expr or child) |
| 78 |
elif isinstance(child, models.Q): |
| 79 |
# this Q object child is another Q object, recursively process |
| 80 |
cpy.children.append(tree_node_correct_field_specs(my_model, child)) |
| 81 |
else: |
| 82 |
cpy.children.append(child) |
| 83 |
return cpy |
| 84 |
|
| 85 |
if isinstance(potential_q_object, models.Q): |
| 86 |
return tree_node_correct_field_specs(queryset_model, potential_q_object) |
| 87 |
|
| 88 |
return potential_q_object # type: ignore[unreachable] |
| 89 |
|
| 90 |
|
| 91 |
def translate_polymorphic_filter_definitions_in_args( |
| 92 |
queryset_model: type[models.Model], args: tuple[Q, ...], using: str = DEFAULT_DB_ALIAS |
| 93 |
) -> list[Q]: |
| 94 |
""" |
| 95 |
Translate the non-keyword argument list for PolymorphicQuerySet.filter() |
| 96 |
|
| 97 |
In the args list, we return all kwargs to Q-objects that contain special |
| 98 |
polymorphic functionality with their vanilla django equivalents. |
| 99 |
We traverse the Q object tree for this (which is simple). |
| 100 |
|
| 101 |
|
| 102 |
Returns: modified Q objects |
| 103 |
""" |
| 104 |
|
| 105 |
return [translate_polymorphic_Q_object(queryset_model, q, using=using) for q in args] |
| 106 |
|
| 107 |
|
| 108 |
def _translate_polymorphic_filter_definition( |
| 109 |
queryset_model: type[models.Model], |
| 110 |
field_path: str, |
| 111 |
field_val: Any, |
| 112 |
using: str = DEFAULT_DB_ALIAS, |
| 113 |
) -> tuple[str, Any] | Q | None: |
| 114 |
""" |
| 115 |
Translate a keyword argument (field_path=field_val), as used for |
| 116 |
PolymorphicQuerySet.filter()-like functions (and Q objects). |
| 117 |
|
| 118 |
A kwarg with special polymorphic functionality is translated into |
| 119 |
its vanilla django equivalent, which is returned, either as tuple |
| 120 |
(field_path, field_val) or as Q object. |
| 121 |
|
| 122 |
Returns: kwarg tuple or Q object or None (if no change is required) |
| 123 |
""" |
| 124 |
|
| 125 |
# handle instance_of expressions or alternatively, |
| 126 |
# if this is a normal Django filter expression, return None |
| 127 |
if field_path == "instance_of": |
| 128 |
return create_instanceof_q(field_val, using=using) |
| 129 |
elif field_path == "not_instance_of": |
| 130 |
return create_instanceof_q(field_val, not_instance_of=True, using=using) |
| 131 |
elif "___" not in field_path: |
| 132 |
return None # no change |
| 133 |
|
| 134 |
# filter expression contains '___' (i.e. filter for polymorphic field) |
| 135 |
# => get the model class specified in the filter expression |
| 136 |
newpath = translate_polymorphic_field_path(queryset_model, field_path) |
| 137 |
return (newpath, field_val) |
| 138 |
|
| 139 |
|
| 140 |
def translate_polymorphic_field_path(queryset_model: type[models.Model], field_path: str) -> str: |
| 141 |
""" |
| 142 |
Translate a field path from a keyword argument, as used for |
| 143 |
PolymorphicQuerySet.filter()-like functions (and Q objects). |
| 144 |
Supports leading '-' (for order_by args). |
| 145 |
|
| 146 |
E.g.: if queryset_model is ModelA, then "ModelC___field3" is translated |
| 147 |
into modela__modelb__modelc__field3. |
| 148 |
Returns: translated path (unchanged, if no translation needed) |
| 149 |
""" |
| 150 |
classname, sep, pure_field_path = field_path.partition("___") |
| 151 |
if not sep or not classname: |
| 152 |
return field_path |
| 153 |
|
| 154 |
negated = False |
| 155 |
if classname[0] == "-": |
| 156 |
negated = True |
| 157 |
classname = classname.lstrip("-") |
| 158 |
|
| 159 |
if "__" in classname: |
| 160 |
# the user has app label prepended to class name via __ => use Django's get_model function |
| 161 |
appname, sep, classname = classname.partition("__") |
| 162 |
try: |
| 163 |
model = apps.get_model(appname, classname) |
| 164 |
except LookupError as le: |
| 165 |
raise FieldError(f"Model {appname}.{classname} does not exist") from le |
| 166 |
if not issubclass(model, queryset_model): |
| 167 |
raise FieldError( |
| 168 |
f"{model._meta.label} is not derived from {queryset_model._meta.label}" |
| 169 |
) |
| 170 |
|
| 171 |
else: |
| 172 |
# the user has only given us the class name via ___ |
| 173 |
# => select the model from the sub models of the queryset base model |
| 174 |
|
| 175 |
# Test whether it's actually a regular relation__ _fieldname (the field starting with an _) |
| 176 |
# so no tripple ClassName___field was intended. |
| 177 |
try: |
| 178 |
# This also retreives M2M relations now (including reverse foreign key relations) |
| 179 |
field = queryset_model._meta.get_field(classname) |
| 180 |
|
| 181 |
if isinstance(field, (RelatedField, ForeignObjectRel)): |
| 182 |
# Can also test whether the field exists in the related object to avoid ambiguity between |
| 183 |
# class names and field names, but that never happens when your class names are in CamelCase. |
| 184 |
return field_path # No exception raised, field does exist. |
| 185 |
except FieldDoesNotExist: |
| 186 |
pass |
| 187 |
|
| 188 |
model = _map_queryname_to_class(queryset_model, classname) |
| 189 |
|
| 190 |
basepath = _create_base_path(queryset_model, model) |
| 191 |
|
| 192 |
if negated: |
| 193 |
newpath = "-" |
| 194 |
else: |
| 195 |
newpath = "" |
| 196 |
|
| 197 |
newpath += basepath |
| 198 |
if basepath: |
| 199 |
newpath += "__" |
| 200 |
|
| 201 |
newpath += pure_field_path |
| 202 |
return newpath |
| 203 |
|
| 204 |
|
| 205 |
def _create_base_path(baseclass: type[models.Model], myclass: type[models.Model]) -> str: |
| 206 |
# create new field path for expressions, e.g. for baseclass=ModelA, myclass=ModelC |
| 207 |
# 'modelb__modelc" is returned |
| 208 |
for b in myclass.__bases__: |
| 209 |
if b == baseclass: |
| 210 |
return _get_query_related_name(myclass) |
| 211 |
|
| 212 |
path = _create_base_path(baseclass, b) |
| 213 |
if path: |
| 214 |
if b._meta.abstract or b._meta.proxy: # type: ignore[attr-defined] |
| 215 |
return _get_query_related_name(myclass) |
| 216 |
else: |
| 217 |
return f"{path}__{_get_query_related_name(myclass)}" |
| 218 |
return "" |
| 219 |
|
| 220 |
|
| 221 |
def _get_query_related_name(myclass: type[models.Model]) -> str: |
| 222 |
for f in myclass._meta.local_fields: |
| 223 |
if isinstance(f, models.OneToOneField) and f.remote_field.parent_link: |
| 224 |
return f.related_query_name() |
| 225 |
|
| 226 |
# Fallback to undetected name, |
| 227 |
# this happens on proxy models (e.g. SubclassSelectorProxyModel) |
| 228 |
return myclass.__name__.lower() |
| 229 |
|
| 230 |
|
| 231 |
def create_instanceof_q( |
| 232 |
modellist: type[models.Model] | list[type[models.Model]] | tuple[type[models.Model], ...], |
| 233 |
not_instance_of: bool = False, |
| 234 |
using: str = DEFAULT_DB_ALIAS, |
| 235 |
) -> Q | None: |
| 236 |
""" |
| 237 |
Helper function for instance_of / not_instance_of |
| 238 |
Creates and returns a Q object that filters for the models in modellist, |
| 239 |
including all subclasses of these models (as we want to do the same |
| 240 |
as pythons isinstance() ). |
| 241 |
. |
| 242 |
We recursively collect all __subclasses__(), create a Q filter for each, |
| 243 |
and or-combine these Q objects. This could be done much more |
| 244 |
efficiently however (regarding the resulting sql), should an optimization |
| 245 |
be needed. |
| 246 |
""" |
| 247 |
if not modellist: |
| 248 |
return None |
| 249 |
|
| 250 |
if not isinstance(modellist, (list, tuple)): |
| 251 |
from .models import PolymorphicModel |
| 252 |
|
| 253 |
if issubclass(modellist, PolymorphicModel): |
| 254 |
modellist = [modellist] |
| 255 |
else: |
| 256 |
raise TypeError( |
| 257 |
"PolymorphicModel: instance_of expects a list of (polymorphic) " |
| 258 |
"models or a single (polymorphic) model" |
| 259 |
) |
| 260 |
|
| 261 |
lazy_cts, ct_ids = _get_mro_content_type_ids(modellist, using) |
| 262 |
q = Q() |
| 263 |
if lazy_cts: |
| 264 |
q |= Q( |
| 265 |
polymorphic_ctype__in=Subquery( |
| 266 |
# no need to pass using here |
| 267 |
ContentType.objects.filter(reduce(or_, lazy_cts)).values("pk") |
| 268 |
) |
| 269 |
) |
| 270 |
if ct_ids: |
| 271 |
q |= Q(polymorphic_ctype__in=ct_ids) |
| 272 |
if not_instance_of: |
| 273 |
q = ~q |
| 274 |
return q |
| 275 |
|
| 276 |
|
| 277 |
def _get_mro_content_type_ids( |
| 278 |
models: list[type[models.Model]] | tuple[type[models.Model], ...], using: str |
| 279 |
) -> tuple[list[Q], list[int]]: |
| 280 |
lazy: list[Q] = [] |
| 281 |
ids: list[int] = [] |
| 282 |
for model in models: |
| 283 |
cid = _lazy_ctype(model, using=using) |
| 284 |
ids.append(cid.pk) if isinstance(cid, ContentType) else lazy.append(cid) |
| 285 |
for descendent in concrete_descendants(model, include_proxy=True): |
| 286 |
cid = _lazy_ctype(descendent, using=using) |
| 287 |
ids.append(cid.pk) if isinstance(cid, ContentType) else lazy.append(cid) |
| 288 |
return lazy, ids |