|
| 1 | +from importlib import import_module |
| 2 | + |
| 3 | +from django.db import IntegrityError, models |
| 4 | +from django.db.models.fields.related import lazy_related_operation |
| 5 | + |
| 6 | + |
| 7 | +class EmbeddedModelField(models.Field): |
| 8 | + """ |
| 9 | + Field that allows you to embed a model instance. |
| 10 | +
|
| 11 | + :param embedded_model: (optional) The model class of instances we |
| 12 | + will be embedding; may also be passed as a |
| 13 | + string, similar to relation fields |
| 14 | +
|
| 15 | + TODO: Make sure to delegate all signals and other field methods to |
| 16 | + the embedded instance (not just pre_save, get_db_prep_* and |
| 17 | + to_python). |
| 18 | + """ |
| 19 | + |
| 20 | + def __init__(self, embedded_model=None, *args, **kwargs): |
| 21 | + self.embedded_model = embedded_model |
| 22 | + super().__init__(*args, **kwargs) |
| 23 | + |
| 24 | + def deconstruct(self): |
| 25 | + name, path, args, kwargs = super().deconstruct() |
| 26 | + if path.startswith("django_mongodb.fields.embedded_model"): |
| 27 | + path = path.replace("django_mongodb.fields.embedded_model", "django_mongodb.fields") |
| 28 | + return name, path, args, kwargs |
| 29 | + |
| 30 | + def get_internal_type(self): |
| 31 | + return "EmbeddedModelField" |
| 32 | + |
| 33 | + def _set_model(self, model): |
| 34 | + """ |
| 35 | + Resolves embedded model class once the field knows the model it |
| 36 | + belongs to. |
| 37 | +
|
| 38 | + If the model argument passed to __init__ was a string, we need |
| 39 | + to make sure to resolve that string to the corresponding model |
| 40 | + class, similar to relation fields. |
| 41 | + However, we need to know our own model to generate a valid key |
| 42 | + for the embedded model class lookup and EmbeddedModelFields are |
| 43 | + not contributed_to_class if used in iterable fields. Thus we |
| 44 | + rely on the collection field telling us its model (by setting |
| 45 | + our "model" attribute in its contribute_to_class method). |
| 46 | + """ |
| 47 | + self._model = model |
| 48 | + if model is not None and isinstance(self.embedded_model, str): |
| 49 | + |
| 50 | + def _resolve_lookup(_, resolved_model): |
| 51 | + self.embedded_model = resolved_model |
| 52 | + |
| 53 | + lazy_related_operation(_resolve_lookup, model, self.embedded_model) |
| 54 | + |
| 55 | + model = property(lambda self: self._model, _set_model) |
| 56 | + |
| 57 | + def stored_model(self, column_values): |
| 58 | + """ |
| 59 | + Returns the fixed embedded_model this field was initialized |
| 60 | + with (typed embedding) or tries to determine the model from |
| 61 | + _module / _model keys stored together with column_values |
| 62 | + (untyped embedding). |
| 63 | +
|
| 64 | + We give precedence to the field's definition model, as silently |
| 65 | + using a differing serialized one could hide some data integrity |
| 66 | + problems. |
| 67 | +
|
| 68 | + Note that a single untyped EmbeddedModelField may process |
| 69 | + instances of different models (especially when used as a type |
| 70 | + of a collection field). |
| 71 | + """ |
| 72 | + module = column_values.pop("_module", None) |
| 73 | + model = column_values.pop("_model", None) |
| 74 | + if self.embedded_model is not None: |
| 75 | + return self.embedded_model |
| 76 | + if module is not None: |
| 77 | + return getattr(import_module(module), model) |
| 78 | + raise IntegrityError( |
| 79 | + "Untyped EmbeddedModelField trying to load data without serialized model class info." |
| 80 | + ) |
| 81 | + |
| 82 | + def from_db_value(self, value, expression, connection): |
| 83 | + return self.to_python(value) |
| 84 | + |
| 85 | + def to_python(self, value): |
| 86 | + """ |
| 87 | + Passes embedded model fields' values through embedded fields |
| 88 | + to_python methods and reinstiatates the embedded instance. |
| 89 | +
|
| 90 | + We expect to receive a field.attname => value dict together |
| 91 | + with a model class from back-end database deconversion (which |
| 92 | + needs to know fields of the model beforehand). |
| 93 | + """ |
| 94 | + # Either the model class has already been determined during |
| 95 | + # deconverting values from the database or we've got a dict |
| 96 | + # from a deserializer that may contain model class info. |
| 97 | + if isinstance(value, tuple): |
| 98 | + embedded_model, attribute_values = value |
| 99 | + elif isinstance(value, dict): |
| 100 | + embedded_model = self.stored_model(value) |
| 101 | + attribute_values = value |
| 102 | + else: |
| 103 | + return value |
| 104 | + # Pass values through respective fields' to_python(), leaving |
| 105 | + # fields for which no value is specified uninitialized. |
| 106 | + attribute_values = { |
| 107 | + field.attname: field.to_python(attribute_values[field.attname]) |
| 108 | + for field in embedded_model._meta.fields |
| 109 | + if field.attname in attribute_values |
| 110 | + } |
| 111 | + # Create the model instance. |
| 112 | + instance = embedded_model(**attribute_values) |
| 113 | + instance._state.adding = False |
| 114 | + return instance |
| 115 | + |
| 116 | + def get_db_prep_save(self, embedded_instance, connection): |
| 117 | + """ |
| 118 | + Apply pre_save() and get_db_prep_save() of embedded instance |
| 119 | + fields and passes a field => value mapping down to database |
| 120 | + type conversions. |
| 121 | +
|
| 122 | + The embedded instance will be saved as a column => value dict |
| 123 | + in the end (possibly augmented with info about instance's model |
| 124 | + for untyped embedding), but because we need to apply database |
| 125 | + type conversions on embedded instance fields' values and for |
| 126 | + these we need to know fields those values come from, we need to |
| 127 | + entrust the database layer with creating the dict. |
| 128 | + """ |
| 129 | + if embedded_instance is None: |
| 130 | + return None |
| 131 | + # The field's value should be an instance of the model given in |
| 132 | + # its declaration or at least of some model. |
| 133 | + embedded_model = self.embedded_model or models.Model |
| 134 | + if not isinstance(embedded_instance, embedded_model): |
| 135 | + raise TypeError( |
| 136 | + f"Expected instance of type {embedded_model!r}, not {type(embedded_instance)!r}." |
| 137 | + ) |
| 138 | + # Apply pre_save() and get_db_prep_save() of embedded instance |
| 139 | + # fields, create the field => value mapping to be passed to |
| 140 | + # storage preprocessing. |
| 141 | + field_values = {} |
| 142 | + add = embedded_instance._state.adding |
| 143 | + for field in embedded_instance._meta.fields: |
| 144 | + value = field.get_db_prep_save( |
| 145 | + field.pre_save(embedded_instance, add), connection=connection |
| 146 | + ) |
| 147 | + # Exclude unset primary keys (e.g. {'id': None}). |
| 148 | + if field.primary_key and value is None: |
| 149 | + continue |
| 150 | + field_values[field.attname] = value |
| 151 | + # Let untyped fields store model info alongside values. |
| 152 | + # Use fake RawFields for additional values to avoid passing |
| 153 | + # embedded_instance to database conversions and to give |
| 154 | + # backends a chance to apply generic conversions. |
| 155 | + if self.embedded_model is None: |
| 156 | + field_values.update( |
| 157 | + ( |
| 158 | + ("_module", embedded_instance.__class__.__module__), |
| 159 | + ("_model", embedded_instance.__class__.__name__), |
| 160 | + ) |
| 161 | + ) |
| 162 | + # This instance will exist in the database soon. |
| 163 | + # TODO.XXX: Ensure that this doesn't cause race conditions. |
| 164 | + embedded_instance._state.adding = False |
| 165 | + return field_values |
0 commit comments