|
1 |
| -from django.db.models import Field |
| 1 | +import difflib |
| 2 | + |
| 3 | +from django.core.exceptions import FieldDoesNotExist |
| 4 | +from django.db.models import Field, lookups |
| 5 | +from django.db.models.expressions import Col |
| 6 | +from django.db.models.lookups import Lookup, Transform |
2 | 7 |
|
3 | 8 | from .. import forms
|
| 9 | +from ..query_utils import process_lhs, process_rhs |
4 | 10 | from . import EmbeddedModelField
|
5 | 11 | from .array import ArrayField
|
6 | 12 |
|
7 | 13 |
|
8 | 14 | class EmbeddedModelArrayField(ArrayField):
|
| 15 | + ALLOWED_LOOKUPS = {"exact", "len", "overlap"} |
| 16 | + |
9 | 17 | def __init__(self, embedded_model, **kwargs):
|
10 | 18 | if "size" in kwargs:
|
11 | 19 | raise ValueError("EmbeddedModelArrayField does not support size.")
|
@@ -44,3 +52,144 @@ def formfield(self, **kwargs):
|
44 | 52 | **kwargs,
|
45 | 53 | },
|
46 | 54 | )
|
| 55 | + |
| 56 | + def get_transform(self, name): |
| 57 | + transform = super().get_transform(name) |
| 58 | + if transform: |
| 59 | + return transform |
| 60 | + return KeyTransformFactory(name, self) |
| 61 | + |
| 62 | + def get_lookup(self, name): |
| 63 | + return super().get_lookup(name) if name in self.ALLOWED_LOOKUPS else None |
| 64 | + |
| 65 | + |
| 66 | +class EMFArrayRHSMixin: |
| 67 | + def check_lhs(self): |
| 68 | + if not isinstance(self.lhs, KeyTransform): |
| 69 | + raise ValueError( |
| 70 | + "Cannot apply this lookup directly to EmbeddedModelArrayField. " |
| 71 | + "Try querying one of its embedded fields instead." |
| 72 | + ) |
| 73 | + |
| 74 | + def process_rhs(self, compiler, connection): |
| 75 | + values = self.rhs |
| 76 | + # Value must be serealized based on the query target. |
| 77 | + # If querying a subfield inside the array (i.e., a nested KeyTransform), use the output |
| 78 | + # field of the subfield. Otherwise, use the base field of the array itself. |
| 79 | + get_db_prep_value = self.lhs._lhs.output_field.get_db_prep_value |
| 80 | + return None, [get_db_prep_value(values, connection, prepared=True)] |
| 81 | + |
| 82 | + |
| 83 | +@EmbeddedModelArrayField.register_lookup |
| 84 | +class EMFArrayExact(EMFArrayRHSMixin, lookups.Exact): |
| 85 | + def as_mql(self, compiler, connection): |
| 86 | + self.check_lhs() |
| 87 | + lhs_mql, inner_lhs_mql = process_lhs(self, compiler, connection) |
| 88 | + value = process_rhs(self, compiler, connection) |
| 89 | + return { |
| 90 | + "$anyElementTrue": { |
| 91 | + "$ifNull": [ |
| 92 | + { |
| 93 | + "$map": { |
| 94 | + "input": lhs_mql, |
| 95 | + "as": "item", |
| 96 | + "in": {"$eq": [inner_lhs_mql, value]}, |
| 97 | + } |
| 98 | + }, |
| 99 | + [], |
| 100 | + ] |
| 101 | + } |
| 102 | + } |
| 103 | + |
| 104 | + |
| 105 | +@EmbeddedModelArrayField.register_lookup |
| 106 | +class ArrayOverlap(EMFArrayRHSMixin, Lookup): |
| 107 | + lookup_name = "overlap" |
| 108 | + |
| 109 | + def as_mql(self, compiler, connection): |
| 110 | + self.check_lhs() |
| 111 | + # Querying a subfield within the array elements (via nested KeyTransform). |
| 112 | + # Replicates MongoDB's implicit ANY-match by mapping over the array and applying |
| 113 | + # `$in` on the subfield. |
| 114 | + lhs_mql = process_lhs(self, compiler, connection) |
| 115 | + values = process_rhs(self, compiler, connection) |
| 116 | + lhs_mql, inner_lhs_mql = lhs_mql |
| 117 | + return { |
| 118 | + "$anyElementTrue": { |
| 119 | + "$ifNull": [ |
| 120 | + { |
| 121 | + "$map": { |
| 122 | + "input": lhs_mql, |
| 123 | + "as": "item", |
| 124 | + "in": {"$in": [inner_lhs_mql, values]}, |
| 125 | + } |
| 126 | + }, |
| 127 | + [], |
| 128 | + ] |
| 129 | + } |
| 130 | + } |
| 131 | + |
| 132 | + |
| 133 | +class KeyTransform(Transform): |
| 134 | + def __init__(self, key_name, array_field, *args, **kwargs): |
| 135 | + super().__init__(*args, **kwargs) |
| 136 | + self.array_field = array_field |
| 137 | + self.key_name = key_name |
| 138 | + # The iteration items begins from the base_field, a virtual column with |
| 139 | + # base field output type is created. |
| 140 | + column_target = array_field.embedded_model._meta.get_field(key_name).clone() |
| 141 | + column_name = f"$item.{key_name}" |
| 142 | + column_target.db_column = column_name |
| 143 | + column_target.set_attributes_from_name(column_name) |
| 144 | + self._lhs = Col(None, column_target) |
| 145 | + self._sub_transform = None |
| 146 | + |
| 147 | + def __call__(self, this, *args, **kwargs): |
| 148 | + self._lhs = self._sub_transform(self._lhs, *args, **kwargs) |
| 149 | + return self |
| 150 | + |
| 151 | + def get_lookup(self, name): |
| 152 | + return self.output_field.get_lookup(name) |
| 153 | + |
| 154 | + def _get_missing_field_or_lookup_exception(self, lhs, name): |
| 155 | + suggested_lookups = difflib.get_close_matches(name, lhs.get_lookups()) |
| 156 | + if suggested_lookups: |
| 157 | + suggested_lookups = " or ".join(suggested_lookups) |
| 158 | + suggestion = f", perhaps you meant {suggested_lookups}?" |
| 159 | + else: |
| 160 | + suggestion = "" |
| 161 | + raise FieldDoesNotExist( |
| 162 | + f"Unsupported lookup '{name}' for " |
| 163 | + f"EmbeddedModelArrayField of '{lhs.__class__.__name__}'" |
| 164 | + f"{suggestion}" |
| 165 | + ) |
| 166 | + |
| 167 | + def get_transform(self, name): |
| 168 | + """ |
| 169 | + Validate that `name` is either a field of an embedded model or a |
| 170 | + lookup on an embedded model's field. |
| 171 | + """ |
| 172 | + # Once the sub lhs is a transform, all the filter are applied over it. |
| 173 | + # Otherwise get transform from EMF. |
| 174 | + if transform := self._lhs.get_transform(name): |
| 175 | + self._sub_transform = transform |
| 176 | + return self |
| 177 | + raise self._get_missing_field_or_lookup_exception(self._lhs.output_field, name) |
| 178 | + |
| 179 | + def as_mql(self, compiler, connection): |
| 180 | + inner_lhs_mql = self._lhs.as_mql(compiler, connection) |
| 181 | + lhs_mql = process_lhs(self, compiler, connection) |
| 182 | + return lhs_mql, inner_lhs_mql |
| 183 | + |
| 184 | + @property |
| 185 | + def output_field(self): |
| 186 | + return self.array_field |
| 187 | + |
| 188 | + |
| 189 | +class KeyTransformFactory: |
| 190 | + def __init__(self, key_name, base_field): |
| 191 | + self.key_name = key_name |
| 192 | + self.base_field = base_field |
| 193 | + |
| 194 | + def __call__(self, *args, **kwargs): |
| 195 | + return KeyTransform(self.key_name, self.base_field, *args, **kwargs) |
0 commit comments