Skip to content

save_mixin

SavePrepareMixin

Bases: RelationMixin, AliasMixin

Used to prepare models to be saved in database

Source code in ormar/models/mixins/save_mixin.py
Python
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
class SavePrepareMixin(RelationMixin, AliasMixin):
    """
    Used to prepare models to be saved in database
    """

    if TYPE_CHECKING:  # pragma: nocover
        _json_fields: set[str]
        _bytes_fields: set[str]
        _onupdate_fields: set[str]
        __pydantic_core_schema__: CoreSchema
        __ormar_fields_validators__: Optional[
            dict[str, Union[SchemaValidator, PluggableSchemaValidator]]
        ]

    @classmethod
    def prepare_model_to_save(cls, new_kwargs: dict) -> dict:
        """
        Combines all preparation methods before saving.
        Removes primary key for if it's nullable or autoincrement pk field,
        and it's set to None.
        Substitute related models with their primary key values as fk column.
        Populates the default values for field with default set and no value.
        Translate columns into aliases (db names).

        :param new_kwargs: dictionary of model that is about to be saved
        :type new_kwargs: dict[str, str]
        :return: dictionary of model that is about to be saved
        :rtype: dict[str, str]
        """
        new_kwargs = cls._remove_pk_from_kwargs(new_kwargs)
        new_kwargs = cls._remove_not_ormar_fields(new_kwargs)
        new_kwargs = cls.substitute_models_with_pks(new_kwargs)
        new_kwargs = cls.populate_default_values(new_kwargs)
        new_kwargs = cls.reconvert_str_to_bytes(new_kwargs)
        new_kwargs = cls.translate_columns_to_aliases(new_kwargs)
        return new_kwargs

    @classmethod
    def prepare_model_to_update(cls, new_kwargs: dict) -> dict:
        """
        Combines all preparation methods before updating.
        :param new_kwargs: dictionary of model that is about to be saved
        :type new_kwargs: dict[str, str]
        :return: dictionary of model that is about to be updated
        :rtype: dict[str, str]
        """
        new_kwargs = cls.substitute_models_with_pks(new_kwargs)
        new_kwargs = cls.reconvert_str_to_bytes(new_kwargs)
        new_kwargs = cls.translate_columns_to_aliases(new_kwargs)
        return new_kwargs

    @classmethod
    def _remove_not_ormar_fields(cls, new_kwargs: dict) -> dict:
        """
        Removes primary key for if it's nullable or autoincrement pk field,
        and it's set to None.

        :param new_kwargs: dictionary of model that is about to be saved
        :type new_kwargs: dict[str, str]
        :return: dictionary of model that is about to be saved
        :rtype: dict[str, str]
        """
        try:
            ormar_fields = cls._ormar_fields_set  # type: ignore[attr-defined]
        except AttributeError:
            ormar_fields = set(cls.ormar_config.model_fields.keys())
            cls._ormar_fields_set = ormar_fields  # type: ignore[attr-defined]
        new_kwargs = {k: v for k, v in new_kwargs.items() if k in ormar_fields}
        return new_kwargs

    @classmethod
    def _remove_pk_from_kwargs(cls, new_kwargs: dict) -> dict:
        """
        Removes primary key for if it's nullable or autoincrement pk field,
        and it's set to None.

        :param new_kwargs: dictionary of model that is about to be saved
        :type new_kwargs: dict[str, str]
        :return: dictionary of model that is about to be saved
        :rtype: dict[str, str]
        """
        for field_name in cls.ormar_config.pk.fields:
            field = cls.ormar_config.model_fields[field_name]
            if new_kwargs.get(field_name, ormar.Undefined) is None and (
                field.nullable or cls.ormar_config.pk.autoincrement
            ):
                del new_kwargs[field_name]
        return new_kwargs

    @classmethod
    def substitute_models_with_pks(cls, model_dict: dict) -> dict:  # noqa  CCR001
        """
        Receives dictionary of model that is about to be saved and changes all related
        models that are stored as foreign keys to their fk value.

        The values of all foreign keys are collected first and merged into the
        dictionary afterwards (see ``merge_relation_values``), so columns the
        foreign keys share get the same result whatever order they come in.

        :param model_dict: dictionary of model that is about to be saved
        :type model_dict: dict
        :return: dictionary of model that is about to be saved
        :rtype: dict
        """
        relation_values: dict[str, dict[str, Any]] = {}
        for field in cls.extract_related_names():
            field_value = model_dict.get(field, None)
            if field_value is None and field in model_dict:
                cls._expand_missing_relation(
                    model_dict=model_dict,
                    field_name=field,
                    relation_values=relation_values,
                )
            elif field_value is not None:
                target_field = cast(
                    "ForeignKeyField", cls.ormar_config.model_fields[field]
                )
                target_key = target_field.to.ormar_config.pk
                if isinstance(field_value, ormar.Model):  # pragma: no cover
                    values = target_field.link.values_for(related=field_value)
                    if None in values.values():
                        raise ModelPersistenceError(
                            f"You cannot save {field_value.get_name()} "
                            f"model without pk set!"
                        )
                    relation_values[field] = values
                elif isinstance(field_value, list) and field_value:
                    model_dict[field] = [
                        target_key.value_from(data=target) for target in field_value
                    ]
                elif isinstance(field_value, dict) and field_value:
                    relation_values[field] = target_field.link.values_for(
                        related=field_value
                    )
                else:
                    model_dict.pop(field, None)
        cls.merge_relation_values(target=model_dict, relation_values=relation_values)
        return model_dict

    @classmethod
    def _expand_missing_relation(
        cls,
        model_dict: dict,
        field_name: str,
        relation_values: dict[str, dict[str, Any]],
    ) -> None:
        """
        A missing foreign key sets all its columns to ``None`` (a column it
        shares with other fields keeps their value), a missing reverse
        relation (one-to-one) is dropped, as it has no column.

        :param model_dict: dictionary of the model that is about to be saved
        :type model_dict: dict
        :param field_name: name of the relation field holding ``None``
        :type field_name: str
        :param relation_values: values of the foreign keys by name, filled in
        :type relation_values: dict[str, dict[str, Any]]
        """
        field = cls.ormar_config.model_fields[field_name]
        if not field.kind.holds_columns:
            model_dict.pop(field_name)
            return
        relation_values[field_name] = cast("ForeignKeyField", field).link.values_for(
            related=None
        )

    @classmethod
    def reconvert_str_to_bytes(cls, model_dict: dict) -> dict:
        """
        Receives dictionary of model that is about to be saved and changes
        all bytes fields that are represented as strings back into bytes.

        :param model_dict: dictionary of model that is about to be saved
        :type model_dict: dict
        :return: dictionary of model that is about to be saved
        :rtype: dict
        """
        bytes_base64_fields = {
            name
            for name, field in cls.ormar_config.model_fields.items()
            if field.represent_as_base64_str
        }
        for key, value in model_dict.items():
            if key in cls._bytes_fields and isinstance(value, str):
                model_dict[key] = (
                    value.encode("utf-8")
                    if key not in bytes_base64_fields
                    else base64.b64decode(value)
                )
        return model_dict

    @classmethod
    def dump_all_json_fields_to_str(cls, model_dict: dict) -> dict:
        """
        Receives dictionary of model that is about to be saved and changes
        all json fields into strings

        :param model_dict: dictionary of model that is about to be saved
        :type model_dict: dict
        :return: dictionary of model that is about to be saved
        :rtype: dict
        """
        for key, value in model_dict.items():
            if key in cls._json_fields:
                model_dict[key] = encode_json(value)
        return model_dict

    @classmethod
    def serialize_nested_models_json_fields(
        cls, kwargs: dict
    ) -> list[tuple["Model", dict[str, Any]]]:
        """
        Serializes JSON fields of related model instances passed in kwargs to
        strings, as pydantic validation of the model validates them again
        against their JSON fields, which only accept strings.

        The related models keep the serialized values only for the validation:
        the decoded values are returned, so they can be restored with
        ``restore_nested_models_json_fields`` afterwards.

        :param kwargs: dictionary of keyword arguments
        :type kwargs: dict
        :return: related models with their decoded JSON field values
        :rtype: list[tuple[Model, dict[str, Any]]]
        """
        decoded = []
        for value in kwargs.values():
            # getattr first, as isinstance on pydantic model metaclass is slow
            json_fields = getattr(value, "_json_fields", None)
            if json_fields and isinstance(value, ormar.Model):
                values = value.__dict__
                decoded.append(
                    (
                        value,
                        {name: values[name] for name in json_fields if name in values},
                    )
                )
                value.dump_all_json_fields_to_str(values)
        return decoded

    @staticmethod
    def restore_nested_models_json_fields(
        decoded: list[tuple["Model", dict[str, Any]]],
    ) -> None:
        """
        Restores decoded JSON field values of related models serialized by
        ``serialize_nested_models_json_fields``.

        :param decoded: related models with their decoded JSON field values
        :type decoded: list[tuple[Model, dict[str, Any]]]
        """
        for model, values in decoded:
            model.__dict__.update(values)

    @classmethod
    def populate_default_values(cls, new_kwargs: dict) -> dict:
        """
        Receives dictionary of model that is about to be saved and populates the default
        value on the fields that have the default value set, but no actual value was
        passed by the user.

        :param new_kwargs: dictionary of model that is about to be saved
        :type new_kwargs: dict
        :return: dictionary of model that is about to be saved
        :rtype: dict
        """
        for field_name, field in cls.ormar_config.model_fields.items():
            if field_name not in new_kwargs and field.has_default(use_server=False):
                new_kwargs[field_name] = field.get_default()
            # clear fields with server_default set as None
            if (
                field.server_default is not None
                and new_kwargs.get(field_name, None) is None
            ):
                new_kwargs.pop(field_name, None)
        return new_kwargs

    @classmethod
    def populate_onupdate_value(
        cls, new_kwargs: dict, explicit_fields: Optional[set[str]] = None
    ) -> dict:
        """
        Populates on_update values for fields that have on_update configured
        and were not provided explicitly.

        If ``explicit_fields`` is omitted the keys of ``new_kwargs`` are
        treated as explicitly provided. Callers pass the set explicitly when
        ``new_kwargs`` is a full ``model_dump`` (e.g. ``bulk_update``) so that
        fields the user actually mutated can be distinguished from values that
        are just present by virtue of the dump.

        :param new_kwargs: dictionary of values about to be used for the update
        :type new_kwargs: dict
        :param explicit_fields: fields that should be considered user-provided
        :type explicit_fields: Optional[set[str]]
        :return: new_kwargs with on_update values populated
        :rtype: dict
        """
        if explicit_fields is None:
            explicit_fields = set(new_kwargs.keys())
        for field_name in cls._onupdate_fields - explicit_fields:
            field = cls.ormar_config.model_fields[field_name]
            new_kwargs[field_name] = field.get_on_update()
        return new_kwargs

    @classmethod
    def validate_update_values(cls, new_kwargs: dict) -> dict:
        """
        Receives dictionary of values about to be set by a queryset update,
        validates them and converts them into column values, the same way
        initializing a model would:

        * foreign keys accept the related model, a dictionary with its pk or the
          pk itself and are replaced with the validated pk value
        * json fields accept a json string or a value to be dumped and are
          replaced with the parsed value
        * other fields are validated with their own validators

        :param new_kwargs: dictionary of values about to be used for the update
        :type new_kwargs: dict
        :return: dictionary of column values about to be used for the update
        :rtype: dict
        """
        validators = cls._build_individual_schema_validator()
        foreign_keys = cls._extract_db_related_names()
        validated: dict = {}
        related_values: dict[str, dict[str, Any]] = {}
        for key, value in new_kwargs.items():
            if key in foreign_keys:
                related_values[key] = cls._related_values_for_update(
                    field_name=key, value=value
                )
            elif key in cls._json_fields:
                validated[key] = validators[key].validate_python(encode_json(value))
            else:
                if key in validators:
                    validators[key].validate_python(value)
                validated[key] = value
        cls.merge_relation_values(target=validated, relation_values=related_values)
        return validated

    @classmethod
    def _related_values_for_update(cls, field_name: str, value: Any) -> dict:
        """
        Returns the validated pk value of a related model passed to a queryset
        update as a model, a dictionary with its pk or the pk itself.

        :param field_name: name of the foreign key field
        :type field_name: str
        :param value: related model, dictionary or pk value (None clears it)
        :type value: Any
        :raises ModelPersistenceError: if the related model has no pk set
        :return: pk value of the related model
        :rtype: Any
        """
        field = cast("ForeignKeyField", cls.ormar_config.model_fields[field_name])
        target = field.to
        is_model = isinstance(value, ormar.Model)
        values = field.link.values_for(related=value)
        if is_model and None in values.values():
            raise ModelPersistenceError(
                f"You cannot update {field_name} with {target.get_name()} "
                f"model without pk set!"
            )
        parts = tuple(values.values())
        if len(parts) > 1 and None in parts and any(part is not None for part in parts):
            raise QueryDefinitionError(
                f"{field_name} needs a value for each of its columns "
                f"{list(values)} (or None), got {value!r}."
            )
        if len(values) == 1:
            ((key, single),) = values.items()
            if single is not None:
                validators = target._build_individual_schema_validator()
                values[key] = validators[field.target_fields()[0]].validate_python(
                    single
                )
        return values

    @classmethod
    def _build_individual_schema_validator(cls) -> Any:
        if cls.__ormar_fields_validators__ is not None:
            return cls.__ormar_fields_validators__
        field_validators = {}
        for key, field in cls._extract_pydantic_fields().items():
            if cls.__pydantic_core_schema__["type"] == "definitions":
                schema = {
                    "type": "definitions",
                    "schema": field["schema"],
                    "definitions": cls.__pydantic_core_schema__["definitions"],
                }
            else:
                schema = field["schema"]
            field_validators[key] = create_schema_validator(
                schema, cls, cls.__module__, cls.__qualname__, "BaseModel"
            )
        cls.__ormar_fields_validators__ = field_validators
        return cls.__ormar_fields_validators__

    @classmethod
    def _extract_pydantic_fields(cls) -> Any:
        if cls.__pydantic_core_schema__["type"] == "model":
            return cls.__pydantic_core_schema__["schema"]["fields"]
        elif cls.__pydantic_core_schema__["type"] == "definitions":
            main_schema = cls.__pydantic_core_schema__["schema"]
            if "schema_ref" in main_schema:  # pragma: no cover
                reference_id = main_schema["schema_ref"]
                return next(
                    ref
                    for ref in cls.__pydantic_core_schema__["definitions"]
                    if ref["ref"] == reference_id
                )["schema"]["fields"]
            return main_schema["schema"]["fields"]

    @staticmethod
    async def _upsert_model(
        instance: "Model",
        save_all: bool,
        previous_model: Optional["Model"],
        relation_field: Optional["ForeignKeyField"],
        update_count: int,
    ) -> int:
        """
        Method updates given instance if:

        * instance is not saved or
        * instance have no pk or
        * save_all=True flag is set

        and instance is not __pk_only__.

        If relation leading to instance is a ManyToMany also the through model is saved

        :param instance: current model to upsert
        :type instance: Model
        :param save_all: flag if all models should be saved or only not saved ones
        :type save_all: bool
        :param relation_field: field with relation
        :type relation_field: Optional[ForeignKeyField]
        :param previous_model: previous model from which method came
        :type previous_model: Model
        :param update_count: no of updated models
        :type update_count: int
        :return: no of updated models
        :rtype: int
        """
        if (
            save_all or not instance.pk or not instance.saved
        ) and not instance.__pk_only__:
            if not instance.ormar_config.view:
                await instance.upsert(__force_save__=True)
            if relation_field and relation_field.is_multi:
                await instance._upsert_through_model(
                    instance=instance,
                    relation_field=relation_field,
                    previous_model=cast("Model", previous_model),
                )
            update_count += 1
        return update_count

    @staticmethod
    async def _upsert_through_model(
        instance: "Model", previous_model: "Model", relation_field: "ForeignKeyField"
    ) -> None:
        """
        Upsert through model for m2m relation.

        :param instance: current model to upsert
        :type instance: Model
        :param relation_field: field with relation
        :type relation_field: Optional[ForeignKeyField]
        :param previous_model: previous model from which method came
        :type previous_model: Model
        """
        through_name = previous_model.ormar_config.model_fields[
            relation_field.name
        ].through.get_name()
        through = getattr(instance, through_name)
        if through:
            through_dict = through.model_dump(exclude=through.extract_related_names())
        else:
            through_dict = {}
        await getattr(
            previous_model, relation_field.name
        ).queryset_proxy.upsert_through_instance(instance, **through_dict)

    async def _update_relation_list(
        self,
        fields_list: Collection["ForeignKeyField"],
        follow: bool,
        save_all: bool,
        relation_map: dict,
        update_count: int,
    ) -> int:
        """
        Internal method used in save_related to follow deeper from
        related models and update numbers of updated related instances.

        :type save_all: flag if all models should be saved
        :type save_all: bool
        :param fields_list: list of ormar fields to follow and save
        :type fields_list: Collection["ForeignKeyField"]
        :param relation_map: map of relations to follow
        :type relation_map: dict
        :param follow: flag to trigger deep save -
        by default only directly related models are saved
        with follow=True also related models of related models are saved
        :type follow: bool
        :param update_count: internal parameter for recursive calls -
        number of updated instances
        :type update_count: int
        :return: tuple of update count and visited
        :rtype: int
        """
        for field in fields_list:
            values = self._get_field_values(name=field.name)
            for value in values:
                if follow:
                    update_count = await value.save_related(
                        follow=follow,
                        save_all=save_all,
                        relation_map=skip_ellipsis(
                            relation_map, field.name, default={}
                        ),
                        update_count=update_count,
                        previous_model=self,
                        relation_field=field,
                    )
                else:
                    update_count = await value._upsert_model(
                        instance=value,
                        save_all=save_all,
                        previous_model=self,
                        relation_field=field,
                        update_count=update_count,
                    )
        return update_count

    def _get_field_values(self, name: str) -> list:
        """
        Extract field values and ensures it is a list.

        :param name: name of the field
        :type name: str
        :return: list of values
        :rtype: list
        """
        values = getattr(self, name) or []
        if not isinstance(values, list):
            values = [values]
        return values

dump_all_json_fields_to_str(model_dict) classmethod

Receives dictionary of model that is about to be saved and changes all json fields into strings

Parameters:

Name Type Description Default
model_dict dict

dictionary of model that is about to be saved

required

Returns:

Type Description
dict

dictionary of model that is about to be saved

Source code in ormar/models/mixins/save_mixin.py
Python
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
@classmethod
def dump_all_json_fields_to_str(cls, model_dict: dict) -> dict:
    """
    Receives dictionary of model that is about to be saved and changes
    all json fields into strings

    :param model_dict: dictionary of model that is about to be saved
    :type model_dict: dict
    :return: dictionary of model that is about to be saved
    :rtype: dict
    """
    for key, value in model_dict.items():
        if key in cls._json_fields:
            model_dict[key] = encode_json(value)
    return model_dict

populate_default_values(new_kwargs) classmethod

Receives dictionary of model that is about to be saved and populates the default value on the fields that have the default value set, but no actual value was passed by the user.

Parameters:

Name Type Description Default
new_kwargs dict

dictionary of model that is about to be saved

required

Returns:

Type Description
dict

dictionary of model that is about to be saved

Source code in ormar/models/mixins/save_mixin.py
Python
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
@classmethod
def populate_default_values(cls, new_kwargs: dict) -> dict:
    """
    Receives dictionary of model that is about to be saved and populates the default
    value on the fields that have the default value set, but no actual value was
    passed by the user.

    :param new_kwargs: dictionary of model that is about to be saved
    :type new_kwargs: dict
    :return: dictionary of model that is about to be saved
    :rtype: dict
    """
    for field_name, field in cls.ormar_config.model_fields.items():
        if field_name not in new_kwargs and field.has_default(use_server=False):
            new_kwargs[field_name] = field.get_default()
        # clear fields with server_default set as None
        if (
            field.server_default is not None
            and new_kwargs.get(field_name, None) is None
        ):
            new_kwargs.pop(field_name, None)
    return new_kwargs

populate_onupdate_value(new_kwargs, explicit_fields=None) classmethod

Populates on_update values for fields that have on_update configured and were not provided explicitly.

If explicit_fields is omitted the keys of new_kwargs are treated as explicitly provided. Callers pass the set explicitly when new_kwargs is a full model_dump (e.g. bulk_update) so that fields the user actually mutated can be distinguished from values that are just present by virtue of the dump.

Parameters:

Name Type Description Default
new_kwargs dict

dictionary of values about to be used for the update

required
explicit_fields Optional[set[str]]

fields that should be considered user-provided

None

Returns:

Type Description
dict

new_kwargs with on_update values populated

Source code in ormar/models/mixins/save_mixin.py
Python
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
@classmethod
def populate_onupdate_value(
    cls, new_kwargs: dict, explicit_fields: Optional[set[str]] = None
) -> dict:
    """
    Populates on_update values for fields that have on_update configured
    and were not provided explicitly.

    If ``explicit_fields`` is omitted the keys of ``new_kwargs`` are
    treated as explicitly provided. Callers pass the set explicitly when
    ``new_kwargs`` is a full ``model_dump`` (e.g. ``bulk_update``) so that
    fields the user actually mutated can be distinguished from values that
    are just present by virtue of the dump.

    :param new_kwargs: dictionary of values about to be used for the update
    :type new_kwargs: dict
    :param explicit_fields: fields that should be considered user-provided
    :type explicit_fields: Optional[set[str]]
    :return: new_kwargs with on_update values populated
    :rtype: dict
    """
    if explicit_fields is None:
        explicit_fields = set(new_kwargs.keys())
    for field_name in cls._onupdate_fields - explicit_fields:
        field = cls.ormar_config.model_fields[field_name]
        new_kwargs[field_name] = field.get_on_update()
    return new_kwargs

prepare_model_to_save(new_kwargs) classmethod

Combines all preparation methods before saving. Removes primary key for if it's nullable or autoincrement pk field, and it's set to None. Substitute related models with their primary key values as fk column. Populates the default values for field with default set and no value. Translate columns into aliases (db names).

Parameters:

Name Type Description Default
new_kwargs dict

dictionary of model that is about to be saved

required

Returns:

Type Description
dict[str, str]

dictionary of model that is about to be saved

Source code in ormar/models/mixins/save_mixin.py
Python
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
@classmethod
def prepare_model_to_save(cls, new_kwargs: dict) -> dict:
    """
    Combines all preparation methods before saving.
    Removes primary key for if it's nullable or autoincrement pk field,
    and it's set to None.
    Substitute related models with their primary key values as fk column.
    Populates the default values for field with default set and no value.
    Translate columns into aliases (db names).

    :param new_kwargs: dictionary of model that is about to be saved
    :type new_kwargs: dict[str, str]
    :return: dictionary of model that is about to be saved
    :rtype: dict[str, str]
    """
    new_kwargs = cls._remove_pk_from_kwargs(new_kwargs)
    new_kwargs = cls._remove_not_ormar_fields(new_kwargs)
    new_kwargs = cls.substitute_models_with_pks(new_kwargs)
    new_kwargs = cls.populate_default_values(new_kwargs)
    new_kwargs = cls.reconvert_str_to_bytes(new_kwargs)
    new_kwargs = cls.translate_columns_to_aliases(new_kwargs)
    return new_kwargs

prepare_model_to_update(new_kwargs) classmethod

Combines all preparation methods before updating.

Parameters:

Name Type Description Default
new_kwargs dict

dictionary of model that is about to be saved

required

Returns:

Type Description
dict[str, str]

dictionary of model that is about to be updated

Source code in ormar/models/mixins/save_mixin.py
Python
58
59
60
61
62
63
64
65
66
67
68
69
70
@classmethod
def prepare_model_to_update(cls, new_kwargs: dict) -> dict:
    """
    Combines all preparation methods before updating.
    :param new_kwargs: dictionary of model that is about to be saved
    :type new_kwargs: dict[str, str]
    :return: dictionary of model that is about to be updated
    :rtype: dict[str, str]
    """
    new_kwargs = cls.substitute_models_with_pks(new_kwargs)
    new_kwargs = cls.reconvert_str_to_bytes(new_kwargs)
    new_kwargs = cls.translate_columns_to_aliases(new_kwargs)
    return new_kwargs

reconvert_str_to_bytes(model_dict) classmethod

Receives dictionary of model that is about to be saved and changes all bytes fields that are represented as strings back into bytes.

Parameters:

Name Type Description Default
model_dict dict

dictionary of model that is about to be saved

required

Returns:

Type Description
dict

dictionary of model that is about to be saved

Source code in ormar/models/mixins/save_mixin.py
Python
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
@classmethod
def reconvert_str_to_bytes(cls, model_dict: dict) -> dict:
    """
    Receives dictionary of model that is about to be saved and changes
    all bytes fields that are represented as strings back into bytes.

    :param model_dict: dictionary of model that is about to be saved
    :type model_dict: dict
    :return: dictionary of model that is about to be saved
    :rtype: dict
    """
    bytes_base64_fields = {
        name
        for name, field in cls.ormar_config.model_fields.items()
        if field.represent_as_base64_str
    }
    for key, value in model_dict.items():
        if key in cls._bytes_fields and isinstance(value, str):
            model_dict[key] = (
                value.encode("utf-8")
                if key not in bytes_base64_fields
                else base64.b64decode(value)
            )
    return model_dict

restore_nested_models_json_fields(decoded) staticmethod

Restores decoded JSON field values of related models serialized by serialize_nested_models_json_fields.

Parameters:

Name Type Description Default
decoded list[tuple[Model, dict[str, Any]]]

related models with their decoded JSON field values

required
Source code in ormar/models/mixins/save_mixin.py
Python
261
262
263
264
265
266
267
268
269
270
271
272
273
@staticmethod
def restore_nested_models_json_fields(
    decoded: list[tuple["Model", dict[str, Any]]],
) -> None:
    """
    Restores decoded JSON field values of related models serialized by
    ``serialize_nested_models_json_fields``.

    :param decoded: related models with their decoded JSON field values
    :type decoded: list[tuple[Model, dict[str, Any]]]
    """
    for model, values in decoded:
        model.__dict__.update(values)

serialize_nested_models_json_fields(kwargs) classmethod

Serializes JSON fields of related model instances passed in kwargs to strings, as pydantic validation of the model validates them again against their JSON fields, which only accept strings.

The related models keep the serialized values only for the validation: the decoded values are returned, so they can be restored with restore_nested_models_json_fields afterwards.

Parameters:

Name Type Description Default
kwargs dict

dictionary of keyword arguments

required

Returns:

Type Description
list[tuple[Model, dict[str, Any]]]

related models with their decoded JSON field values

Source code in ormar/models/mixins/save_mixin.py
Python
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
@classmethod
def serialize_nested_models_json_fields(
    cls, kwargs: dict
) -> list[tuple["Model", dict[str, Any]]]:
    """
    Serializes JSON fields of related model instances passed in kwargs to
    strings, as pydantic validation of the model validates them again
    against their JSON fields, which only accept strings.

    The related models keep the serialized values only for the validation:
    the decoded values are returned, so they can be restored with
    ``restore_nested_models_json_fields`` afterwards.

    :param kwargs: dictionary of keyword arguments
    :type kwargs: dict
    :return: related models with their decoded JSON field values
    :rtype: list[tuple[Model, dict[str, Any]]]
    """
    decoded = []
    for value in kwargs.values():
        # getattr first, as isinstance on pydantic model metaclass is slow
        json_fields = getattr(value, "_json_fields", None)
        if json_fields and isinstance(value, ormar.Model):
            values = value.__dict__
            decoded.append(
                (
                    value,
                    {name: values[name] for name in json_fields if name in values},
                )
            )
            value.dump_all_json_fields_to_str(values)
    return decoded

substitute_models_with_pks(model_dict) classmethod

Receives dictionary of model that is about to be saved and changes all related models that are stored as foreign keys to their fk value.

The values of all foreign keys are collected first and merged into the dictionary afterwards (see merge_relation_values), so columns the foreign keys share get the same result whatever order they come in.

Parameters:

Name Type Description Default
model_dict dict

dictionary of model that is about to be saved

required

Returns:

Type Description
dict

dictionary of model that is about to be saved

Source code in ormar/models/mixins/save_mixin.py
Python
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
@classmethod
def substitute_models_with_pks(cls, model_dict: dict) -> dict:  # noqa  CCR001
    """
    Receives dictionary of model that is about to be saved and changes all related
    models that are stored as foreign keys to their fk value.

    The values of all foreign keys are collected first and merged into the
    dictionary afterwards (see ``merge_relation_values``), so columns the
    foreign keys share get the same result whatever order they come in.

    :param model_dict: dictionary of model that is about to be saved
    :type model_dict: dict
    :return: dictionary of model that is about to be saved
    :rtype: dict
    """
    relation_values: dict[str, dict[str, Any]] = {}
    for field in cls.extract_related_names():
        field_value = model_dict.get(field, None)
        if field_value is None and field in model_dict:
            cls._expand_missing_relation(
                model_dict=model_dict,
                field_name=field,
                relation_values=relation_values,
            )
        elif field_value is not None:
            target_field = cast(
                "ForeignKeyField", cls.ormar_config.model_fields[field]
            )
            target_key = target_field.to.ormar_config.pk
            if isinstance(field_value, ormar.Model):  # pragma: no cover
                values = target_field.link.values_for(related=field_value)
                if None in values.values():
                    raise ModelPersistenceError(
                        f"You cannot save {field_value.get_name()} "
                        f"model without pk set!"
                    )
                relation_values[field] = values
            elif isinstance(field_value, list) and field_value:
                model_dict[field] = [
                    target_key.value_from(data=target) for target in field_value
                ]
            elif isinstance(field_value, dict) and field_value:
                relation_values[field] = target_field.link.values_for(
                    related=field_value
                )
            else:
                model_dict.pop(field, None)
    cls.merge_relation_values(target=model_dict, relation_values=relation_values)
    return model_dict

validate_update_values(new_kwargs) classmethod

Receives dictionary of values about to be set by a queryset update, validates them and converts them into column values, the same way initializing a model would:

  • foreign keys accept the related model, a dictionary with its pk or the pk itself and are replaced with the validated pk value
  • json fields accept a json string or a value to be dumped and are replaced with the parsed value
  • other fields are validated with their own validators

Parameters:

Name Type Description Default
new_kwargs dict

dictionary of values about to be used for the update

required

Returns:

Type Description
dict

dictionary of column values about to be used for the update

Source code in ormar/models/mixins/save_mixin.py
Python
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
@classmethod
def validate_update_values(cls, new_kwargs: dict) -> dict:
    """
    Receives dictionary of values about to be set by a queryset update,
    validates them and converts them into column values, the same way
    initializing a model would:

    * foreign keys accept the related model, a dictionary with its pk or the
      pk itself and are replaced with the validated pk value
    * json fields accept a json string or a value to be dumped and are
      replaced with the parsed value
    * other fields are validated with their own validators

    :param new_kwargs: dictionary of values about to be used for the update
    :type new_kwargs: dict
    :return: dictionary of column values about to be used for the update
    :rtype: dict
    """
    validators = cls._build_individual_schema_validator()
    foreign_keys = cls._extract_db_related_names()
    validated: dict = {}
    related_values: dict[str, dict[str, Any]] = {}
    for key, value in new_kwargs.items():
        if key in foreign_keys:
            related_values[key] = cls._related_values_for_update(
                field_name=key, value=value
            )
        elif key in cls._json_fields:
            validated[key] = validators[key].validate_python(encode_json(value))
        else:
            if key in validators:
                validators[key].validate_python(value)
            validated[key] = value
    cls.merge_relation_values(target=validated, relation_values=related_values)
    return validated