Skip to content

mixins

Package contains functionalities divided by features. All mixins are combined into ModelTableProxy which is one of the parents of Model. The split into mixins was done to ease the maintainability of the proxy class, as it became quite complicated over time.

AliasMixin

Used to translate field names into database column names.

Source code in ormar/models/mixins/alias_mixin.py
Python
 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
class AliasMixin:
    """
    Used to translate field names into database column names.
    """

    if TYPE_CHECKING:  # pragma: no cover
        from ormar.models.ormar_config import OrmarConfig

        ormar_config: OrmarConfig

    _alias_to_field_map: dict[str, str]
    _field_to_alias_map: dict[str, str]
    _column_to_field_map: dict[str, str]
    _multi_column_fields: tuple[tuple[str, tuple[str, ...]], ...]
    _column_owners_map: dict[str, tuple[str, ...]]
    _shared_value_keys: dict[str, SharedKey]
    _shared_plain_fields: tuple[SharedPlainField, ...]
    _column_readers: dict[str, "ColumnReader"]

    @classmethod
    def _build_alias_cache(cls) -> None:
        """
        Build and cache alias mappings for this model class.
        Builds:
        - _field_to_alias_map: field_name -> db_alias
        - _alias_to_field_map: db_alias -> field_name (reverse)
        - _column_to_field_map: every table column -> field storing it (the
          columns of a foreign key stored in several columns map to it too)
        - _multi_column_fields: (field_name, columns) of such foreign keys
        """
        field_to_alias = {}
        for field_name, field in cls.ormar_config.model_fields.items():
            alias = field.get_alias()
            if alias:
                field_to_alias[field_name] = alias
        cls._field_to_alias_map = field_to_alias
        cls._alias_to_field_map = ormar_rust_utils.build_reverse_alias_map(
            field_to_alias
        )
        column_to_field = dict(cls._alias_to_field_map)
        multi_column_fields = []
        owners: dict[str, list[str]] = {}
        for field_name, field in cls.ormar_config.model_fields.items():
            if field.virtual or field.is_multi:
                continue
            columns = field.column_aliases()
            for column in columns:
                owners.setdefault(column, []).append(field_name)
            if field.is_relation and len(columns) > 1:
                multi_column_fields.append((field_name, columns))
                for column in columns:
                    column_to_field.setdefault(column, field_name)
        cls._column_to_field_map = column_to_field
        cls._multi_column_fields = tuple(multi_column_fields)
        cls._column_owners_map = {
            column: tuple(names) for column, names in owners.items()
        }
        cls._shared_value_keys = cls._build_shared_value_keys(owners=owners)
        cls._shared_plain_fields = cls._build_shared_plain_fields(owners=owners)

    @classmethod
    def _build_shared_value_keys(
        cls, owners: dict[str, list[str]]
    ) -> dict[str, SharedKey]:
        """
        For every column stored by several fields, map the key each of them
        stores its value under in a model dict (the field name, or the column
        for a foreign key stored in several columns) to where the column's
        value is kept.

        :param owners: fields storing each column
        :type owners: dict[str, list[str]]
        :return: ``{value key: SharedKey}``
        :rtype: dict[str, SharedKey]
        """
        model_fields = cls.ormar_config.model_fields
        shared: dict[str, SharedKey] = {}
        for column, names in owners.items():
            if len(names) == 1:
                continue
            keys = [
                column if len(model_fields[name].column_aliases()) > 1 else name
                for name in names
            ]
            plain = [name for name in names if not model_fields[name].is_relation]
            kept = plain[0] if plain else keys[0]
            shared.update({key: SharedKey(kept=kept, column=column) for key in keys})
        return shared

    @classmethod
    def _build_shared_plain_fields(
        cls, owners: dict[str, list[str]]
    ) -> tuple[SharedPlainField, ...]:
        """
        :param owners: fields storing each column
        :type owners: dict[str, list[str]]
        :return: the plain fields storing a column foreign keys share
        :rtype: tuple[SharedPlainField, ...]
        """
        model_fields = cls.ormar_config.model_fields
        plain_fields = []
        for column, names in owners.items():
            plain = [name for name in names if not model_fields[name].is_relation]
            if len(names) == 1 or not plain:
                continue
            sources = tuple(
                (
                    name,
                    column if len(model_fields[name].column_aliases()) > 1 else name,
                )
                for name in names
                if model_fields[name].is_relation
            )
            plain_fields.append(SharedPlainField(field=plain[0], sources=sources))
        return tuple(plain_fields)

    @classmethod
    def reset_column_caches(cls) -> None:
        """
        Drop the cached column mappings of the model and the layout of its
        primary key, e.g. after forward references are resolved and a foreign
        key's columns are known.
        """
        for name in (
            "_field_to_alias_map",
            "_alias_to_field_map",
            "_column_to_field_map",
            "_multi_column_fields",
            "_column_owners_map",
            "_shared_value_keys",
            "_shared_plain_fields",
            "_table_column_pairs",
            "_column_readers",
        ):
            if name in cls.__dict__:
                delattr(cls, name)
        cls.ormar_config.pk.cached_layout = None

    @classmethod
    def get_field_name_of_column(cls, column: str) -> str:
        """
        Returns the ormar field storing a table column, also for the columns
        of a foreign key stored in several columns.

        :param column: column name in the database
        :type column: str
        :return: field name, the column itself if no field is aliased to it
        :rtype: str
        """
        try:
            return cls._column_to_field_map.get(column, column)
        except AttributeError:
            cls._build_alias_cache()
            return cls._column_to_field_map.get(column, column)

    @classmethod
    def translate_row_to_fields(cls, row: dict) -> dict:
        """
        Translates a database row of the model's table into field values: the
        columns of a foreign key stored in several columns become one tuple
        (``None`` when any of them is null).

        :param row: column values by column name
        :type row: dict
        :return: field values by field name
        :rtype: dict
        """
        values = cls.translate_aliases_to_columns(row)
        columns_read: set[str] = set()
        for field_name, columns in cls._multi_column_fields:
            parts = tuple(values.get(column) for column in columns)
            values[field_name] = None if None in parts else parts
            columns_read.update(columns)
        model_fields = cls.ormar_config.model_fields
        for column in columns_read:
            if column not in model_fields:
                values.pop(column, None)
        return values

    @classmethod
    def get_field_names_of_column(cls, column: str) -> tuple[str, ...]:
        """
        :param column: column name in the database
        :type column: str
        :return: every ormar field storing the column, in declaration order
            (several when fields share it)
        :rtype: tuple[str, ...]
        """
        try:
            owners = cls._column_owners_map
        except AttributeError:
            cls._build_alias_cache()
            owners = cls._column_owners_map
        return owners.get(column) or (cls.get_field_name_of_column(column=column),)

    @classmethod
    def column_reader(cls, column: str) -> "ColumnReader":
        """
        :param column: column name in the database
        :type column: str
        :return: cached reader of the column's raw value out of an instance of
            the model, its key-only model or a dict of its fields (see
            ``ormar.fields.link.column_reader``)
        :rtype: ColumnReader
        """
        readers = cls.__dict__.get("_column_readers")
        if readers is None:
            readers = {}
            cls._column_readers = readers
        reader = readers.get(column)
        if reader is None:
            reader = column_reader(model=cast("type[Model]", cls), column=column)
            readers[column] = reader
        return reader

    @classmethod
    def shared_value_keys(cls) -> dict[str, SharedKey]:
        """
        :return: for the keys of columns several fields share, the key the
            column's value is kept under and the column (see
            ``_build_shared_value_keys``)
        :rtype: dict[str, SharedKey]
        """
        try:
            return cls._shared_value_keys
        except AttributeError:
            cls._build_alias_cache()
            return cls._shared_value_keys

    @classmethod
    def fill_shared_plain_fields(cls, kwargs: dict[str, Any]) -> None:
        """
        Fill an unset plain field storing a column foreign keys share from
        the first of those foreign keys holding a value for the column, so a
        new model's plain field, ``model_dump()`` and ``pk`` agree before it
        is saved.

        :param kwargs: keyword arguments of a model being initialized, with
            relations already expanded, updated in place
        :type kwargs: dict[str, Any]
        """
        try:
            plain_fields = cls._shared_plain_fields
        except AttributeError:
            cls._build_alias_cache()
            plain_fields = cls._shared_plain_fields
        model_fields = cls.ormar_config.model_fields
        for plain in plain_fields:
            if kwargs.get(plain.field) is not None:
                continue
            for field_name, key in plain.sources:
                related = kwargs.get(field_name)
                if related is None:
                    continue
                link = cast("ForeignKeyField", model_fields[field_name]).link
                value = link.values_for(related=related)[key]
                if value is not None:
                    kwargs[plain.field] = value
                    break

    @classmethod
    def value_keys(cls, field_name: str) -> tuple[str, ...]:
        """
        :param field_name: name of a field stored in the model's table
        :type field_name: str
        :return: keys the field's values are kept under in a model dict about
            to be written: its name, or its columns for a foreign key stored
            in several columns; a shared column under the key it is kept under
        :rtype: tuple[str, ...]
        """
        shared = cls.shared_value_keys()
        field = cls.ormar_config.model_fields[field_name]
        columns = field.column_aliases()
        keys = columns if field.is_relation and len(columns) > 1 else (field_name,)
        return tuple(shared[key].kept if key in shared else key for key in keys)

    @classmethod
    def merge_relation_values(
        cls, target: dict, relation_values: dict[str, dict[str, Any]]
    ) -> None:
        """
        Put the values foreign keys store (``RelationLink.values_for``) into a
        model dict about to be written. The foreign keys' own entries are
        dropped from the dict first, then their values are merged in the
        order the fields are declared, so the result never depends on the
        order the foreign keys were processed in.

        A column several fields share keeps one value: a ``None`` is not
        written to it while another of its fields holds a value (a shared
        column is cleared only when every foreign key storing it is cleared
        and no plain field stores it), an unset plain field sharing the
        column is filled in, and two different values are an error.

        :raises ModelPersistenceError: if a shared column gets two values
        :param target: model dict being prepared, updated in place
        :type target: dict
        :param relation_values: values of each foreign key by key, by foreign
            key name
        :type relation_values: dict[str, dict[str, Any]]
        """
        for field_name in relation_values:
            target.pop(field_name, None)
        shared = cls.shared_value_keys()
        if not shared:
            for values in relation_values.values():
                target.update(values)
            return
        cleared: dict[SharedKey, int] = {}
        for field_name in cls.ormar_config.model_fields:
            field_values = relation_values.get(field_name)
            if field_values is None:
                continue
            for key, value in field_values.items():
                if key not in shared:
                    target[key] = value
                    continue
                kept, column = shared[key]
                current = target.get(kept)
                if value is None:
                    cleared[shared[key]] = cleared.get(shared[key], 0) + 1
                    continue
                if current is None:
                    target[kept] = value
                elif value != current:
                    raise ModelPersistenceError(
                        f"{cls.__name__}.{field_name} stores {value!r} in column "
                        f"{column}, which another field sets to {current!r}."
                    )
        cls.clear_shared_columns(target=target, cleared=cleared)

    @classmethod
    def clear_shared_columns(cls, target: dict, cleared: dict[SharedKey, int]) -> None:
        """
        Write ``None`` to a shared column when every field storing it is a
        foreign key given ``None`` (e.g. two nullable foreign keys sharing a
        ``tenant_id`` both set to ``None``). The fields are counted per column,
        as foreign keys stored in several columns all keep a shared column
        under the same key, and a plain field storing the column is never
        cleared, so its column keeps its value.

        :param target: model dict being prepared, updated in place
        :type target: dict
        :param cleared: number of foreign keys given ``None`` per shared column
        :type cleared: dict[SharedKey, int]
        """
        for (kept, column), count in cleared.items():
            sharing = len(cls.get_field_names_of_column(column=column))
            if target.get(kept) is None and count == sharing:
                target[kept] = None

    @classmethod
    def get_column_alias(cls, field_name: str) -> str:
        """
        Returns db alias (column name in db) for given ormar field.
        For fields without alias field name is returned.
        :param field_name: name of the field to get alias from
        :type field_name: str
        :return: alias (db name) if set, otherwise passed name
        :rtype: str
        """
        try:
            return cls._field_to_alias_map.get(field_name, field_name)
        except AttributeError:
            cls._build_alias_cache()
            return cls._field_to_alias_map.get(field_name, field_name)

    @classmethod
    def get_column_aliases(cls, field_name: str) -> tuple[str, ...]:
        """
        Returns db column names of given ormar field: one for most fields,
        several for a foreign key stored in several columns.

        :param field_name: name of the field
        :type field_name: str
        :return: column names of the field
        :rtype: tuple[str, ...]
        """
        field = cls.ormar_config.model_fields.get(field_name)
        if field is None:
            return (cls.get_column_alias(field_name=field_name),)
        return field.column_aliases()

    @classmethod
    def get_column_name_from_alias(cls, alias: str) -> str:
        """
        Returns ormar field name for given db alias (column name in db).
        If field do not have alias it's returned as is.
        :param alias:
        :type alias: str
        :return: field name if set, otherwise passed alias (db name)
        :rtype: str
        """
        try:
            return cls._alias_to_field_map.get(alias, alias)
        except AttributeError:
            cls._build_alias_cache()
            return cls._alias_to_field_map.get(alias, alias)

    @classmethod
    def translate_columns_to_aliases(cls, new_kwargs: dict) -> dict:
        """
        Translates dictionary of model fields changing field names into aliases.
        If field has no alias the field name remains intact.
        Only fields present in the dictionary are translated.
        :param new_kwargs: dict with fields names and their values
        :type new_kwargs: dict
        :return: dict with aliases and their values
        :rtype: dict
        """
        try:
            field_to_alias = cls._field_to_alias_map
        except AttributeError:
            cls._build_alias_cache()
            field_to_alias = cls._field_to_alias_map
        for field_name in list(new_kwargs.keys()):
            alias = field_to_alias.get(field_name)
            if alias and alias != field_name:
                new_kwargs[alias] = new_kwargs.pop(field_name)
        return new_kwargs

    @classmethod
    def translate_aliases_to_columns(cls, new_kwargs: dict) -> dict:
        """
        Translates dictionary of model fields changing aliases into field names.
        If field has no alias the alias is already a field name.
        Only fields present in the dictionary are translated.
        :param new_kwargs: dict with aliases and their values
        :type new_kwargs: dict
        :return: dict with fields names and their values
        :rtype: dict
        """
        try:
            alias_to_field = cls._alias_to_field_map
        except AttributeError:  # pragma: nocover
            cls._build_alias_cache()
            alias_to_field = cls._alias_to_field_map
        for key in list(new_kwargs.keys()):
            field_name = alias_to_field.get(key)
            if field_name and field_name != key:
                new_kwargs[field_name] = new_kwargs.pop(key)
        return new_kwargs

clear_shared_columns(target, cleared) classmethod

Write None to a shared column when every field storing it is a foreign key given None (e.g. two nullable foreign keys sharing a tenant_id both set to None). The fields are counted per column, as foreign keys stored in several columns all keep a shared column under the same key, and a plain field storing the column is never cleared, so its column keeps its value.

Parameters:

Name Type Description Default
target dict

model dict being prepared, updated in place

required
cleared dict[SharedKey, int]

number of foreign keys given None per shared column

required
Source code in ormar/models/mixins/alias_mixin.py
Python
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
@classmethod
def clear_shared_columns(cls, target: dict, cleared: dict[SharedKey, int]) -> None:
    """
    Write ``None`` to a shared column when every field storing it is a
    foreign key given ``None`` (e.g. two nullable foreign keys sharing a
    ``tenant_id`` both set to ``None``). The fields are counted per column,
    as foreign keys stored in several columns all keep a shared column
    under the same key, and a plain field storing the column is never
    cleared, so its column keeps its value.

    :param target: model dict being prepared, updated in place
    :type target: dict
    :param cleared: number of foreign keys given ``None`` per shared column
    :type cleared: dict[SharedKey, int]
    """
    for (kept, column), count in cleared.items():
        sharing = len(cls.get_field_names_of_column(column=column))
        if target.get(kept) is None and count == sharing:
            target[kept] = None

column_reader(column) classmethod

Parameters:

Name Type Description Default
column str

column name in the database

required

Returns:

Type Description
ColumnReader

cached reader of the column's raw value out of an instance of the model, its key-only model or a dict of its fields (see ormar.fields.link.column_reader)

Source code in ormar/models/mixins/alias_mixin.py
Python
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
@classmethod
def column_reader(cls, column: str) -> "ColumnReader":
    """
    :param column: column name in the database
    :type column: str
    :return: cached reader of the column's raw value out of an instance of
        the model, its key-only model or a dict of its fields (see
        ``ormar.fields.link.column_reader``)
    :rtype: ColumnReader
    """
    readers = cls.__dict__.get("_column_readers")
    if readers is None:
        readers = {}
        cls._column_readers = readers
    reader = readers.get(column)
    if reader is None:
        reader = column_reader(model=cast("type[Model]", cls), column=column)
        readers[column] = reader
    return reader

fill_shared_plain_fields(kwargs) classmethod

Fill an unset plain field storing a column foreign keys share from the first of those foreign keys holding a value for the column, so a new model's plain field, model_dump() and pk agree before it is saved.

Parameters:

Name Type Description Default
kwargs dict[str, Any]

keyword arguments of a model being initialized, with relations already expanded, updated in place

required
Source code in ormar/models/mixins/alias_mixin.py
Python
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
@classmethod
def fill_shared_plain_fields(cls, kwargs: dict[str, Any]) -> None:
    """
    Fill an unset plain field storing a column foreign keys share from
    the first of those foreign keys holding a value for the column, so a
    new model's plain field, ``model_dump()`` and ``pk`` agree before it
    is saved.

    :param kwargs: keyword arguments of a model being initialized, with
        relations already expanded, updated in place
    :type kwargs: dict[str, Any]
    """
    try:
        plain_fields = cls._shared_plain_fields
    except AttributeError:
        cls._build_alias_cache()
        plain_fields = cls._shared_plain_fields
    model_fields = cls.ormar_config.model_fields
    for plain in plain_fields:
        if kwargs.get(plain.field) is not None:
            continue
        for field_name, key in plain.sources:
            related = kwargs.get(field_name)
            if related is None:
                continue
            link = cast("ForeignKeyField", model_fields[field_name]).link
            value = link.values_for(related=related)[key]
            if value is not None:
                kwargs[plain.field] = value
                break

get_column_alias(field_name) classmethod

Returns db alias (column name in db) for given ormar field. For fields without alias field name is returned.

Parameters:

Name Type Description Default
field_name str

name of the field to get alias from

required

Returns:

Type Description
str

alias (db name) if set, otherwise passed name

Source code in ormar/models/mixins/alias_mixin.py
Python
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
@classmethod
def get_column_alias(cls, field_name: str) -> str:
    """
    Returns db alias (column name in db) for given ormar field.
    For fields without alias field name is returned.
    :param field_name: name of the field to get alias from
    :type field_name: str
    :return: alias (db name) if set, otherwise passed name
    :rtype: str
    """
    try:
        return cls._field_to_alias_map.get(field_name, field_name)
    except AttributeError:
        cls._build_alias_cache()
        return cls._field_to_alias_map.get(field_name, field_name)

get_column_aliases(field_name) classmethod

Returns db column names of given ormar field: one for most fields, several for a foreign key stored in several columns.

Parameters:

Name Type Description Default
field_name str

name of the field

required

Returns:

Type Description
tuple[str, ...]

column names of the field

Source code in ormar/models/mixins/alias_mixin.py
Python
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
@classmethod
def get_column_aliases(cls, field_name: str) -> tuple[str, ...]:
    """
    Returns db column names of given ormar field: one for most fields,
    several for a foreign key stored in several columns.

    :param field_name: name of the field
    :type field_name: str
    :return: column names of the field
    :rtype: tuple[str, ...]
    """
    field = cls.ormar_config.model_fields.get(field_name)
    if field is None:
        return (cls.get_column_alias(field_name=field_name),)
    return field.column_aliases()

get_column_name_from_alias(alias) classmethod

Returns ormar field name for given db alias (column name in db). If field do not have alias it's returned as is.

Parameters:

Name Type Description Default
alias str
required

Returns:

Type Description
str

field name if set, otherwise passed alias (db name)

Source code in ormar/models/mixins/alias_mixin.py
Python
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
@classmethod
def get_column_name_from_alias(cls, alias: str) -> str:
    """
    Returns ormar field name for given db alias (column name in db).
    If field do not have alias it's returned as is.
    :param alias:
    :type alias: str
    :return: field name if set, otherwise passed alias (db name)
    :rtype: str
    """
    try:
        return cls._alias_to_field_map.get(alias, alias)
    except AttributeError:
        cls._build_alias_cache()
        return cls._alias_to_field_map.get(alias, alias)

get_field_name_of_column(column) classmethod

Returns the ormar field storing a table column, also for the columns of a foreign key stored in several columns.

Parameters:

Name Type Description Default
column str

column name in the database

required

Returns:

Type Description
str

field name, the column itself if no field is aliased to it

Source code in ormar/models/mixins/alias_mixin.py
Python
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
@classmethod
def get_field_name_of_column(cls, column: str) -> str:
    """
    Returns the ormar field storing a table column, also for the columns
    of a foreign key stored in several columns.

    :param column: column name in the database
    :type column: str
    :return: field name, the column itself if no field is aliased to it
    :rtype: str
    """
    try:
        return cls._column_to_field_map.get(column, column)
    except AttributeError:
        cls._build_alias_cache()
        return cls._column_to_field_map.get(column, column)

get_field_names_of_column(column) classmethod

Parameters:

Name Type Description Default
column str

column name in the database

required

Returns:

Type Description
tuple[str, ...]

every ormar field storing the column, in declaration order (several when fields share it)

Source code in ormar/models/mixins/alias_mixin.py
Python
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
@classmethod
def get_field_names_of_column(cls, column: str) -> tuple[str, ...]:
    """
    :param column: column name in the database
    :type column: str
    :return: every ormar field storing the column, in declaration order
        (several when fields share it)
    :rtype: tuple[str, ...]
    """
    try:
        owners = cls._column_owners_map
    except AttributeError:
        cls._build_alias_cache()
        owners = cls._column_owners_map
    return owners.get(column) or (cls.get_field_name_of_column(column=column),)

merge_relation_values(target, relation_values) classmethod

Put the values foreign keys store (RelationLink.values_for) into a model dict about to be written. The foreign keys' own entries are dropped from the dict first, then their values are merged in the order the fields are declared, so the result never depends on the order the foreign keys were processed in.

A column several fields share keeps one value: a None is not written to it while another of its fields holds a value (a shared column is cleared only when every foreign key storing it is cleared and no plain field stores it), an unset plain field sharing the column is filled in, and two different values are an error.

Parameters:

Name Type Description Default
target dict

model dict being prepared, updated in place

required
relation_values dict[str, dict[str, Any]]

values of each foreign key by key, by foreign key name

required

Raises:

Type Description
ModelPersistenceError

if a shared column gets two values

Source code in ormar/models/mixins/alias_mixin.py
Python
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
@classmethod
def merge_relation_values(
    cls, target: dict, relation_values: dict[str, dict[str, Any]]
) -> None:
    """
    Put the values foreign keys store (``RelationLink.values_for``) into a
    model dict about to be written. The foreign keys' own entries are
    dropped from the dict first, then their values are merged in the
    order the fields are declared, so the result never depends on the
    order the foreign keys were processed in.

    A column several fields share keeps one value: a ``None`` is not
    written to it while another of its fields holds a value (a shared
    column is cleared only when every foreign key storing it is cleared
    and no plain field stores it), an unset plain field sharing the
    column is filled in, and two different values are an error.

    :raises ModelPersistenceError: if a shared column gets two values
    :param target: model dict being prepared, updated in place
    :type target: dict
    :param relation_values: values of each foreign key by key, by foreign
        key name
    :type relation_values: dict[str, dict[str, Any]]
    """
    for field_name in relation_values:
        target.pop(field_name, None)
    shared = cls.shared_value_keys()
    if not shared:
        for values in relation_values.values():
            target.update(values)
        return
    cleared: dict[SharedKey, int] = {}
    for field_name in cls.ormar_config.model_fields:
        field_values = relation_values.get(field_name)
        if field_values is None:
            continue
        for key, value in field_values.items():
            if key not in shared:
                target[key] = value
                continue
            kept, column = shared[key]
            current = target.get(kept)
            if value is None:
                cleared[shared[key]] = cleared.get(shared[key], 0) + 1
                continue
            if current is None:
                target[kept] = value
            elif value != current:
                raise ModelPersistenceError(
                    f"{cls.__name__}.{field_name} stores {value!r} in column "
                    f"{column}, which another field sets to {current!r}."
                )
    cls.clear_shared_columns(target=target, cleared=cleared)

reset_column_caches() classmethod

Drop the cached column mappings of the model and the layout of its primary key, e.g. after forward references are resolved and a foreign key's columns are known.

Source code in ormar/models/mixins/alias_mixin.py
Python
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
@classmethod
def reset_column_caches(cls) -> None:
    """
    Drop the cached column mappings of the model and the layout of its
    primary key, e.g. after forward references are resolved and a foreign
    key's columns are known.
    """
    for name in (
        "_field_to_alias_map",
        "_alias_to_field_map",
        "_column_to_field_map",
        "_multi_column_fields",
        "_column_owners_map",
        "_shared_value_keys",
        "_shared_plain_fields",
        "_table_column_pairs",
        "_column_readers",
    ):
        if name in cls.__dict__:
            delattr(cls, name)
    cls.ormar_config.pk.cached_layout = None

shared_value_keys() classmethod

Returns:

Type Description
dict[str, SharedKey]

for the keys of columns several fields share, the key the column's value is kept under and the column (see _build_shared_value_keys)

Source code in ormar/models/mixins/alias_mixin.py
Python
256
257
258
259
260
261
262
263
264
265
266
267
268
@classmethod
def shared_value_keys(cls) -> dict[str, SharedKey]:
    """
    :return: for the keys of columns several fields share, the key the
        column's value is kept under and the column (see
        ``_build_shared_value_keys``)
    :rtype: dict[str, SharedKey]
    """
    try:
        return cls._shared_value_keys
    except AttributeError:
        cls._build_alias_cache()
        return cls._shared_value_keys

translate_aliases_to_columns(new_kwargs) classmethod

Translates dictionary of model fields changing aliases into field names. If field has no alias the alias is already a field name. Only fields present in the dictionary are translated.

Parameters:

Name Type Description Default
new_kwargs dict

dict with aliases and their values

required

Returns:

Type Description
dict

dict with fields names and their values

Source code in ormar/models/mixins/alias_mixin.py
Python
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
@classmethod
def translate_aliases_to_columns(cls, new_kwargs: dict) -> dict:
    """
    Translates dictionary of model fields changing aliases into field names.
    If field has no alias the alias is already a field name.
    Only fields present in the dictionary are translated.
    :param new_kwargs: dict with aliases and their values
    :type new_kwargs: dict
    :return: dict with fields names and their values
    :rtype: dict
    """
    try:
        alias_to_field = cls._alias_to_field_map
    except AttributeError:  # pragma: nocover
        cls._build_alias_cache()
        alias_to_field = cls._alias_to_field_map
    for key in list(new_kwargs.keys()):
        field_name = alias_to_field.get(key)
        if field_name and field_name != key:
            new_kwargs[field_name] = new_kwargs.pop(key)
    return new_kwargs

translate_columns_to_aliases(new_kwargs) classmethod

Translates dictionary of model fields changing field names into aliases. If field has no alias the field name remains intact. Only fields present in the dictionary are translated.

Parameters:

Name Type Description Default
new_kwargs dict

dict with fields names and their values

required

Returns:

Type Description
dict

dict with aliases and their values

Source code in ormar/models/mixins/alias_mixin.py
Python
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
@classmethod
def translate_columns_to_aliases(cls, new_kwargs: dict) -> dict:
    """
    Translates dictionary of model fields changing field names into aliases.
    If field has no alias the field name remains intact.
    Only fields present in the dictionary are translated.
    :param new_kwargs: dict with fields names and their values
    :type new_kwargs: dict
    :return: dict with aliases and their values
    :rtype: dict
    """
    try:
        field_to_alias = cls._field_to_alias_map
    except AttributeError:
        cls._build_alias_cache()
        field_to_alias = cls._field_to_alias_map
    for field_name in list(new_kwargs.keys()):
        alias = field_to_alias.get(field_name)
        if alias and alias != field_name:
            new_kwargs[alias] = new_kwargs.pop(field_name)
    return new_kwargs

translate_row_to_fields(row) classmethod

Translates a database row of the model's table into field values: the columns of a foreign key stored in several columns become one tuple (None when any of them is null).

Parameters:

Name Type Description Default
row dict

column values by column name

required

Returns:

Type Description
dict

field values by field name

Source code in ormar/models/mixins/alias_mixin.py
Python
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
@classmethod
def translate_row_to_fields(cls, row: dict) -> dict:
    """
    Translates a database row of the model's table into field values: the
    columns of a foreign key stored in several columns become one tuple
    (``None`` when any of them is null).

    :param row: column values by column name
    :type row: dict
    :return: field values by field name
    :rtype: dict
    """
    values = cls.translate_aliases_to_columns(row)
    columns_read: set[str] = set()
    for field_name, columns in cls._multi_column_fields:
        parts = tuple(values.get(column) for column in columns)
        values[field_name] = None if None in parts else parts
        columns_read.update(columns)
    model_fields = cls.ormar_config.model_fields
    for column in columns_read:
        if column not in model_fields:
            values.pop(column, None)
    return values

value_keys(field_name) classmethod

Parameters:

Name Type Description Default
field_name str

name of a field stored in the model's table

required

Returns:

Type Description
tuple[str, ...]

keys the field's values are kept under in a model dict about to be written: its name, or its columns for a foreign key stored in several columns; a shared column under the key it is kept under

Source code in ormar/models/mixins/alias_mixin.py
Python
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
@classmethod
def value_keys(cls, field_name: str) -> tuple[str, ...]:
    """
    :param field_name: name of a field stored in the model's table
    :type field_name: str
    :return: keys the field's values are kept under in a model dict about
        to be written: its name, or its columns for a foreign key stored
        in several columns; a shared column under the key it is kept under
    :rtype: tuple[str, ...]
    """
    shared = cls.shared_value_keys()
    field = cls.ormar_config.model_fields[field_name]
    columns = field.column_aliases()
    keys = columns if field.is_relation and len(columns) > 1 else (field_name,)
    return tuple(shared[key].kept if key in shared else key for key in keys)

ExcludableMixin

Bases: RelationMixin

Used to include/exclude given set of fields on models during load and dict() calls.

Source code in ormar/models/mixins/excludable_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
class ExcludableMixin(RelationMixin):
    """
    Used to include/exclude given set of fields on models during load and dict() calls.
    """

    if TYPE_CHECKING:  # pragma: no cover
        from ormar import Model
        from ormar.models import ModelRow

    @staticmethod
    def _populate_pk_columns(
        model: Union[type["Model"], type["ModelRow"]],
        columns: list[str],
        use_alias: bool = False,
    ) -> list[str]:
        """
        Adds the primary key columns/aliases (depends on use_alias flag) missing
        from the list of column names that are selected.

        :param model: model on columns are selected
        :type model: type["Model"]
        :param columns: list of columns names
        :type columns: list[str]
        :param use_alias: flag to set if aliases or field names should be used
        :type use_alias: bool
        :return: list of columns names with pk column in it
        :rtype: list[str]
        """
        key = model.ormar_config.pk
        names = key.column_aliases() if use_alias else key.fields
        for name in names:
            if name not in columns:
                columns.append(name)
        return columns

    @staticmethod
    def _get_table_column_pairs(
        model: Union[type["Model"], type["ModelRow"]],
    ) -> list[tuple[str, str]]:
        """
        Returns cached list of (col_name, field_name) tuples for the model's table,
        one per field storing the column (several for a shared column).
        Built once per model class and cached to avoid repeated SA column iteration.

        :param model: model to get column pairs for
        :type model: type["Model"]
        :return: list of (column_name, field_name) tuples
        :rtype: list[tuple[str, str]]
        """
        cached = getattr(model, "_table_column_pairs", None)
        if cached is not None:
            return cached
        pairs = [
            (col.name, field_name)
            for col in model.ormar_config.table.columns
            for field_name in model.get_field_names_of_column(column=col.name)
        ]
        model._table_column_pairs = pairs  # type: ignore[union-attr]
        return pairs

    @classmethod
    def own_table_columns(
        cls,
        model: Union[type["Model"], type["ModelRow"]],
        excludable: ExcludableItems,
        alias: str = "",
        use_alias: bool = False,
        add_pk_columns: bool = True,
    ) -> list[str]:
        """
        Returns list of aliases or field names for given model.
        Aliases/names switch is use_alias flag.

        If provided only fields included in fields will be returned.
        If provided fields in exclude_fields will be excluded in return.

        Primary key field is always added and cannot be excluded (will be added anyway).

        :param add_pk_columns: flag if add primary key - always yes if ormar parses data
        :type add_pk_columns: bool
        :param alias: relation prefix
        :type alias: str
        :param excludable: structure of fields to include and exclude
        :type excludable: ExcludableItems
        :param model: model on columns are selected
        :type model: type["Model"]
        :param use_alias: flag if aliases or field names should be used
        :type use_alias: bool
        :return: list of column field names or aliases
        :rtype: list[str]
        """
        model_excludable = excludable.get(model_cls=model, alias=alias)  # type: ignore
        if model_excludable.pk_only:
            if not add_pk_columns:
                return []
            return cls._populate_pk_columns(
                model=model, columns=[], use_alias=use_alias
            )
        has_include = bool(model_excludable.include)
        has_exclude = bool(model_excludable.exclude)

        column_pairs = cls._get_table_column_pairs(model)
        columns = []
        for col_name, field_name in column_pairs:
            if has_include and not model_excludable.is_included(field_name):
                continue
            if has_exclude and model_excludable.is_excluded(field_name):
                continue
            name = col_name if use_alias else field_name
            if name not in columns:
                columns.append(name)

        # always has to return pk column for ormar to work
        if add_pk_columns:
            columns = cls._populate_pk_columns(
                model=model, columns=columns, use_alias=use_alias
            )

        return columns

    @classmethod
    def _update_excluded_with_related(cls, exclude: Union[set, dict, None]) -> set:
        """
        Used during generation of the dict().
        To avoid cyclical references and max recurrence limit nested models have to
        exclude related models that are not mandatory.

        For a main model (not nested) only nullable related field names are added to
        exclusion, for nested models all related models are excluded.

        :param exclude: set/dict with fields to exclude
        :type exclude: Union[set, dict, None]
        :return: set or dict with excluded fields added.
        :rtype: Union[set, dict]
        """
        exclude = exclude or set()
        related_set = cls.extract_related_names()
        if isinstance(exclude, set):
            exclude = {s for s in exclude}
            exclude = exclude.union(related_set)
        elif isinstance(exclude, dict):
            # relations are handled in ormar - take only own fields (ellipsis in dict)
            exclude = {k for k, v in exclude.items() if v is Ellipsis}
            exclude = exclude.union(related_set)
        return exclude

    @classmethod
    def _update_excluded_with_pks_and_through(
        cls, exclude: set, exclude_primary_keys: bool, exclude_through_models: bool
    ) -> set:
        """
        Updates excluded names with name of pk column if exclude flag is set.

        :param exclude: set of names to exclude
        :type exclude: set
        :param exclude_primary_keys: flag if the primary keys should be excluded
        :type exclude_primary_keys: bool
        :return: set updated with pk if flag is set
        :rtype: set
        """
        if exclude_primary_keys:
            exclude.update(cls.ormar_config.pk.fields)
        if exclude_through_models:
            exclude = exclude.union(cls.extract_through_names())
        return exclude

    @classmethod
    def get_names_to_exclude(cls, excludable: ExcludableItems, alias: str) -> set:
        """
        Returns a set of models field names that should be explicitly excluded
        during model initialization.

        Those fields will be set to None to avoid ormar/pydantic setting default
        values on them. They should be returned as None in any case.

        Used in parsing data from database rows that construct Models by initializing
        them with dicts constructed from those db rows.

        :param alias: alias of current relation
        :type alias: str
        :param excludable: structure of fields to include and exclude
        :type excludable: ExcludableItems
        :return: set of field names that should be excluded
        :rtype: set
        """
        model = cast(type["Model"], cls)
        model_excludable = excludable.get(model_cls=model, alias=alias)
        fields_names = cls.extract_db_own_fields()
        if model_excludable.include:
            fields_to_keep = model_excludable.include.intersection(fields_names)
        else:
            fields_to_keep = fields_names

        fields_to_exclude = fields_names - fields_to_keep

        if model_excludable.exclude:
            fields_to_exclude = fields_to_exclude.union(
                model_excludable.exclude.intersection(fields_names)
            )
        fields_to_exclude = fields_to_exclude - set(cls.ormar_config.pk.fields)

        return fields_to_exclude

get_names_to_exclude(excludable, alias) classmethod

Returns a set of models field names that should be explicitly excluded during model initialization.

Those fields will be set to None to avoid ormar/pydantic setting default values on them. They should be returned as None in any case.

Used in parsing data from database rows that construct Models by initializing them with dicts constructed from those db rows.

Parameters:

Name Type Description Default
alias str

alias of current relation

required
excludable ExcludableItems

structure of fields to include and exclude

required

Returns:

Type Description
set

set of field names that should be excluded

Source code in ormar/models/mixins/excludable_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
211
212
213
214
215
216
217
218
219
220
221
222
@classmethod
def get_names_to_exclude(cls, excludable: ExcludableItems, alias: str) -> set:
    """
    Returns a set of models field names that should be explicitly excluded
    during model initialization.

    Those fields will be set to None to avoid ormar/pydantic setting default
    values on them. They should be returned as None in any case.

    Used in parsing data from database rows that construct Models by initializing
    them with dicts constructed from those db rows.

    :param alias: alias of current relation
    :type alias: str
    :param excludable: structure of fields to include and exclude
    :type excludable: ExcludableItems
    :return: set of field names that should be excluded
    :rtype: set
    """
    model = cast(type["Model"], cls)
    model_excludable = excludable.get(model_cls=model, alias=alias)
    fields_names = cls.extract_db_own_fields()
    if model_excludable.include:
        fields_to_keep = model_excludable.include.intersection(fields_names)
    else:
        fields_to_keep = fields_names

    fields_to_exclude = fields_names - fields_to_keep

    if model_excludable.exclude:
        fields_to_exclude = fields_to_exclude.union(
            model_excludable.exclude.intersection(fields_names)
        )
    fields_to_exclude = fields_to_exclude - set(cls.ormar_config.pk.fields)

    return fields_to_exclude

own_table_columns(model, excludable, alias='', use_alias=False, add_pk_columns=True) classmethod

Returns list of aliases or field names for given model. Aliases/names switch is use_alias flag.

If provided only fields included in fields will be returned. If provided fields in exclude_fields will be excluded in return.

Primary key field is always added and cannot be excluded (will be added anyway).

Parameters:

Name Type Description Default
add_pk_columns bool

flag if add primary key - always yes if ormar parses data

True
alias str

relation prefix

''
excludable ExcludableItems

structure of fields to include and exclude

required
model Union[type[Model], type[ModelRow]]

model on columns are selected

required
use_alias bool

flag if aliases or field names should be used

False

Returns:

Type Description
list[str]

list of column field names or aliases

Source code in ormar/models/mixins/excludable_mixin.py
Python
 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
@classmethod
def own_table_columns(
    cls,
    model: Union[type["Model"], type["ModelRow"]],
    excludable: ExcludableItems,
    alias: str = "",
    use_alias: bool = False,
    add_pk_columns: bool = True,
) -> list[str]:
    """
    Returns list of aliases or field names for given model.
    Aliases/names switch is use_alias flag.

    If provided only fields included in fields will be returned.
    If provided fields in exclude_fields will be excluded in return.

    Primary key field is always added and cannot be excluded (will be added anyway).

    :param add_pk_columns: flag if add primary key - always yes if ormar parses data
    :type add_pk_columns: bool
    :param alias: relation prefix
    :type alias: str
    :param excludable: structure of fields to include and exclude
    :type excludable: ExcludableItems
    :param model: model on columns are selected
    :type model: type["Model"]
    :param use_alias: flag if aliases or field names should be used
    :type use_alias: bool
    :return: list of column field names or aliases
    :rtype: list[str]
    """
    model_excludable = excludable.get(model_cls=model, alias=alias)  # type: ignore
    if model_excludable.pk_only:
        if not add_pk_columns:
            return []
        return cls._populate_pk_columns(
            model=model, columns=[], use_alias=use_alias
        )
    has_include = bool(model_excludable.include)
    has_exclude = bool(model_excludable.exclude)

    column_pairs = cls._get_table_column_pairs(model)
    columns = []
    for col_name, field_name in column_pairs:
        if has_include and not model_excludable.is_included(field_name):
            continue
        if has_exclude and model_excludable.is_excluded(field_name):
            continue
        name = col_name if use_alias else field_name
        if name not in columns:
            columns.append(name)

    # always has to return pk column for ormar to work
    if add_pk_columns:
        columns = cls._populate_pk_columns(
            model=model, columns=columns, use_alias=use_alias
        )

    return columns

MergeModelMixin

Used to collect models instances returned by database, but already initialized to ormar Models.

Rows of one model returned by a join are materialized into a single shared instance (see RowRegistry), so the same main model can repeat in the list of materialized rows; in the end all main models should be unique.

Source code in ormar/models/mixins/merge_mixin.py
Python
 8
 9
10
11
12
13
14
15
16
17
18
19
20
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
class MergeModelMixin:
    """
    Used to collect models instances returned by database,
    but already initialized to ormar Models.

    Rows of one model returned by a join are materialized into a single shared
    instance (see ``RowRegistry``), so the same main model can repeat in the
    list of materialized rows; in the end all main models should be unique.
    """

    @classmethod
    def merge_instances_list(
        cls,
        result_rows: list["Model"],
        *,
        excludable: "ExcludableItems",
    ) -> list["Model"]:
        """
        Collapses a list of materialized rows into a list of unique models,
        keeping the order of first occurrence.

        Each top-level model also has the queryset's ``ExcludableItems``
        attached via the ``__ormar_excludable__`` slot so a bare ``model_dump()``
        on the result can resolve the (lazily cached) flatten map without going
        back through the queryset.

        :param result_rows: list of models materialized from consecutive rows,
            where rows of the same main model resolve to the same instance
        :type result_rows: list["Model"]
        :param excludable: ExcludableItems to attach to every top-level
            instance via the ``__ormar_excludable__`` slot
        :type excludable: ExcludableItems
        :return: list of unique main models
        :rtype: list["Model"]
        """
        merged_rows: list["Model"] = []
        seen: set[int] = set()
        for model in result_rows:
            if id(model) in seen:
                continue
            seen.add(id(model))
            object.__setattr__(model, "__ormar_excludable__", excludable)
            merged_rows.append(model)
        return merged_rows

merge_instances_list(result_rows, *, excludable) classmethod

Collapses a list of materialized rows into a list of unique models, keeping the order of first occurrence.

Each top-level model also has the queryset's ExcludableItems attached via the __ormar_excludable__ slot so a bare model_dump() on the result can resolve the (lazily cached) flatten map without going back through the queryset.

Parameters:

Name Type Description Default
result_rows list[Model]

list of models materialized from consecutive rows, where rows of the same main model resolve to the same instance

required
excludable ExcludableItems

ExcludableItems to attach to every top-level instance via the __ormar_excludable__ slot

required

Returns:

Type Description
list["Model"]

list of unique main models

Source code in ormar/models/mixins/merge_mixin.py
Python
18
19
20
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
@classmethod
def merge_instances_list(
    cls,
    result_rows: list["Model"],
    *,
    excludable: "ExcludableItems",
) -> list["Model"]:
    """
    Collapses a list of materialized rows into a list of unique models,
    keeping the order of first occurrence.

    Each top-level model also has the queryset's ``ExcludableItems``
    attached via the ``__ormar_excludable__`` slot so a bare ``model_dump()``
    on the result can resolve the (lazily cached) flatten map without going
    back through the queryset.

    :param result_rows: list of models materialized from consecutive rows,
        where rows of the same main model resolve to the same instance
    :type result_rows: list["Model"]
    :param excludable: ExcludableItems to attach to every top-level
        instance via the ``__ormar_excludable__`` slot
    :type excludable: ExcludableItems
    :return: list of unique main models
    :rtype: list["Model"]
    """
    merged_rows: list["Model"] = []
    seen: set[int] = set()
    for model in result_rows:
        if id(model) in seen:
            continue
        seen.add(id(model))
        object.__setattr__(model, "__ormar_excludable__", excludable)
        merged_rows.append(model)
    return merged_rows

PydanticMixin

Bases: RelationMixin

Source code in ormar/models/mixins/pydantic_mixin.py
Python
 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
class PydanticMixin(RelationMixin):
    __cache__: dict[tuple[type, str, str, str], type[pydantic.BaseModel]] = {}

    if TYPE_CHECKING:  # pragma: no cover
        __pydantic_decorators__: DecoratorInfos

    @classmethod
    def get_pydantic(
        cls,
        *,
        include: Union[set, dict, None] = None,
        exclude: Union[set, dict, None] = None,
        flatten_fields: Union[
            set, list, str, tuple, dict, "FieldAccessor", None
        ] = None,
        flatten_all: bool = False,
        max_depth: Optional[int] = None,
        omit_back_relations: Optional[bool] = None,
    ) -> type[pydantic.BaseModel]:
        """
        Returns a pydantic model out of ormar model.

        Converts also nested ormar models into pydantic models. Each related
        model is generated once as a named nested model and relations point to
        it, so cyclic relations give recursive models (``$ref`` in OpenAPI).
        Relation fields of nested models are optional, the root model keeps
        the required/optional rules of its own fields. Generated models are
        cached and their names do not depend on the order of calls
        (``Book``, ``Book_nested``, ``Book_depth2``, a selector hash suffix).

        Can be used to fully exclude certain fields in fastapi response and requests.

        Relations listed in ``flatten_fields`` (or all relations with
        ``flatten_all``) are represented by the related model's primary key
        (or a list of primary keys for many-to-many and reverse relations)
        instead of a nested pydantic model, matching the output of
        ``model_dump`` called with the same arguments.

        :param include: fields of own and nested models to include
        :type include: Union[set, dict, None]
        :param exclude: fields of own and nested models to exclude
        :type exclude: Union[set, dict, None]
        :param flatten_fields: relations to represent as their primary key
        :type flatten_fields: Union[set, list, str, tuple, dict, FieldAccessor, None]
        :param flatten_all: if True every relation is represented as its pk
        :type flatten_all: bool
        :param max_depth: number of relation levels to nest at most, None for
            no limit (cycles become recursive models)
        :type max_depth: Optional[int]
        :param omit_back_relations: leave the relation back to the parent out
            of nested models (one nested model per (model, relation) pair),
            False by default (one nested model per model)
        :type omit_back_relations: Optional[bool]
        :raises QueryDefinitionError: on invalid flatten paths or when a
            flattened relation has sub-field include/exclude
        """
        flatten_map = resolve_flatten_map(
            model_cls=cast(type["Model"], cls),
            flatten_fields=flatten_fields,
            flatten_all=flatten_all,
        )
        if flatten_map is not None:
            flatten_map.check_vs_selector(normalize_to_dict(include), "include")
            flatten_map.check_vs_selector(normalize_to_dict(exclude), "exclude")

        if (
            instance_traversal_enabled()
            or max_depth is not None
            or omit_back_relations is not None
        ):
            return RecursiveSchemaBuilder(
                omit_back_relations=bool(omit_back_relations)
            ).build(
                model=cls,
                include=include,
                exclude=exclude,
                flatten_map=flatten_map,
                max_depth=max_depth,
            )
        return cls._convert_ormar_to_pydantic(
            include=include,
            exclude=exclude,
            flatten_map=flatten_map,
            relation_map=cls._relation_tree(),
        )

    @classmethod
    def _convert_ormar_to_pydantic(
        cls,
        relation_map: dict[str, Any],
        include: Union[set, dict, None] = None,
        exclude: Union[set, dict, None] = None,
        flatten_map: Optional[FlattenMap] = None,
    ) -> type[pydantic.BaseModel]:
        include = normalize_to_dict(include)
        exclude = normalize_to_dict(exclude)
        fields_dict: dict[str, Any] = dict()
        defaults: dict[str, Any] = dict()
        fields_to_process = filter_not_excluded_fields(
            fields={*cls.ormar_config.model_fields.keys()},
            include=include,
            exclude=exclude,
        )
        fields_to_process.sort(
            key=lambda x: list(cls.ormar_config.model_fields.keys()).index(x)
        )

        cache_key = (cls, str(include), str(exclude), str(flatten_map))
        if cache_key in cls.__cache__:
            return cls.__cache__[cache_key]

        for name in fields_to_process:
            field = cls._determine_pydantic_field_type(
                name=name,
                defaults=defaults,
                include=include,
                exclude=exclude,
                flatten_map=flatten_map,
                relation_map=relation_map,
            )
            if field is not None:
                fields_dict[name] = field
        model = type(
            f"{cls.__name__}_{''.join(choices(string.ascii_uppercase, k=3))}",
            (pydantic.BaseModel,),
            {"__annotations__": fields_dict, **defaults},
        )
        model = cast(type[pydantic.BaseModel], model)
        cls._copy_computed_fields(model=model, include=include, exclude=exclude)
        cls._copy_field_validators(model=model)
        cls.__cache__[cache_key] = model
        return model

    @classmethod
    def _determine_pydantic_field_type(
        cls,
        name: str,
        defaults: dict,
        include: Union[set, dict, None],
        exclude: Union[set, dict, None],
        flatten_map: Optional[FlattenMap],
        relation_map: dict[str, Any],
    ) -> Any:
        field = cls.ormar_config.model_fields[name]
        target: Any = None
        if field.is_relation and name in relation_map:
            if flatten_map and flatten_map.is_field_flattened(name):
                target = cls._determine_flattened_relation_field_type(
                    name=name, field=field, defaults=defaults
                )
            else:
                target = cls._determined_included_relation_field_type(
                    name=name,
                    field=field,
                    include=include,
                    exclude=exclude,
                    flatten_map=flatten_map.descend(name) if flatten_map else None,
                    defaults=defaults,
                    relation_map=relation_map,
                )
        elif not field.is_relation:
            defaults[name] = cls.model_fields[name].default  # type: ignore
            target = field.__type__
        if target is not None and field.nullable:
            target = Optional[target]
        return target

    @classmethod
    def _determined_included_relation_field_type(
        cls,
        name: str,
        field: Union[BaseField, ForeignKeyField, ManyToManyField],
        include: Union[set, dict, None],
        exclude: Union[set, dict, None],
        flatten_map: Optional[FlattenMap],
        defaults: dict,
        relation_map: dict[str, Any],
    ) -> Any:
        target = field.to._convert_ormar_to_pydantic(
            include=skip_ellipsis(include, name),
            exclude=skip_ellipsis(exclude, name),
            flatten_map=flatten_map,
            relation_map=cast(
                dict[str, Any], skip_ellipsis(relation_map, name, default=dict())
            ),
        )
        return cls._wrap_relation_field_type(
            name=name, field=field, target=target, defaults=defaults
        )

    @classmethod
    def _determine_flattened_relation_field_type(
        cls,
        name: str,
        field: Union[BaseField, ForeignKeyField, ManyToManyField],
        defaults: dict,
    ) -> Any:
        """
        Build the pydantic type of a flattened relation: the related
        model's pk type with a before-validator that reduces nested dicts and
        model instances to their pk value.

        :param name: name of the relation field
        :type name: str
        :param field: ormar relation field
        :type field: Union[BaseField, ForeignKeyField, ManyToManyField]
        :param defaults: default values of the generated pydantic model
        :type defaults: dict
        :return: pydantic annotation of the field
        :rtype: Any
        """
        relation_field = cast("ForeignKeyField", field)
        target: Any = Annotated[
            relation_field.flat_value_type(),  # type: ignore
            BeforeValidator(
                partial(extract_pk_value, fields=relation_field.flat_fields())
            ),
        ]
        return cls._wrap_relation_field_type(
            name=name, field=field, target=target, defaults=defaults
        )

    @staticmethod
    def _wrap_relation_field_type(
        name: str,
        field: Union[BaseField, ForeignKeyField, ManyToManyField],
        target: Any,
        defaults: dict,
    ) -> Any:
        """
        Wrap relation target type in a list for multi and reverse relations and
        register a ``None`` default for nullable relations.

        :param name: name of the relation field
        :type name: str
        :param field: ormar relation field
        :type field: Union[BaseField, ForeignKeyField, ManyToManyField]
        :param target: pydantic type of a single related item
        :type target: Any
        :param defaults: default values of the generated pydantic model
        :type defaults: dict
        :return: pydantic annotation of the field
        :rtype: Any
        """
        if field.kind.many:
            target = list[target]  # type: ignore
        if field.nullable:
            defaults[name] = None
        return target

    @classmethod
    def _copy_computed_fields(
        cls,
        model: type[pydantic.BaseModel],
        include: Optional[dict],
        exclude: Optional[dict],
    ) -> None:
        """
        Copy ``@pydantic.computed_field`` decorated methods from the ormar model
        onto the generated pydantic model so they are exposed in the schema and
        serialization output. Computed fields are filtered with the same
        include/exclude rules as regular fields.

        :param model: pydantic model generated from the ormar model
        :type model: type[pydantic.BaseModel]
        :param include: fields of own and nested models to include
        :type include: Optional[dict]
        :param exclude: fields of own and nested models to exclude
        :type exclude: Optional[dict]
        """
        computed_fields = cls.__pydantic_decorators__.computed_fields
        if not computed_fields:
            return
        names_to_copy = filter_not_excluded_fields(
            fields=set(computed_fields.keys()),
            include=include,
            exclude=exclude,
        )
        for name in names_to_copy:
            decorator = computed_fields[name]
            setattr(model, name, decorator.info.wrapped_property)
            model.__pydantic_decorators__.computed_fields[name] = copy.copy(decorator)

    @classmethod
    def _copy_field_validators(
        cls, model: type[pydantic.BaseModel], rebuild: bool = True
    ) -> None:
        """
        Copy field validators from ormar model to generated pydantic model.

        :param model: pydantic model generated from the ormar model
        :type model: type[pydantic.BaseModel]
        :param rebuild: rebuild the model right away, False when its forward
            references are resolved later
        :type rebuild: bool
        """
        filed_names = list(model.model_fields.keys())
        cls.copy_selected_validators_type(
            model=model, fields=filed_names, validator_type="field_validators"
        )
        cls.copy_selected_validators_type(
            model=model, fields=filed_names, validator_type="validators"
        )

        class_validators = cls.__pydantic_decorators__.root_validators
        model.__pydantic_decorators__.root_validators.update(
            copy.deepcopy(class_validators)
        )
        model_validators = cls.__pydantic_decorators__.model_validators
        model.__pydantic_decorators__.model_validators.update(
            copy.deepcopy(model_validators)
        )
        if rebuild:
            model.model_rebuild(force=True)

    @classmethod
    def copy_selected_validators_type(
        cls, model: type[pydantic.BaseModel], fields: list[str], validator_type: str
    ) -> None:
        """
        Copy field validators from ormar model to generated pydantic model.
        """
        validators = getattr(cls.__pydantic_decorators__, validator_type)
        for name, decorator in validators.items():
            if any(field_name in decorator.info.fields for field_name in fields):
                copied_decorator = copy.deepcopy(decorator)
                copied_decorator.info.fields = [
                    field_name
                    for field_name in decorator.info.fields
                    if field_name in fields
                ]
                getattr(model.__pydantic_decorators__, validator_type)[name] = (
                    copied_decorator
                )

copy_selected_validators_type(model, fields, validator_type) classmethod

Copy field validators from ormar model to generated pydantic model.

Source code in ormar/models/mixins/pydantic_mixin.py
Python
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
@classmethod
def copy_selected_validators_type(
    cls, model: type[pydantic.BaseModel], fields: list[str], validator_type: str
) -> None:
    """
    Copy field validators from ormar model to generated pydantic model.
    """
    validators = getattr(cls.__pydantic_decorators__, validator_type)
    for name, decorator in validators.items():
        if any(field_name in decorator.info.fields for field_name in fields):
            copied_decorator = copy.deepcopy(decorator)
            copied_decorator.info.fields = [
                field_name
                for field_name in decorator.info.fields
                if field_name in fields
            ]
            getattr(model.__pydantic_decorators__, validator_type)[name] = (
                copied_decorator
            )

get_pydantic(*, include=None, exclude=None, flatten_fields=None, flatten_all=False, max_depth=None, omit_back_relations=None) classmethod

Returns a pydantic model out of ormar model.

Converts also nested ormar models into pydantic models. Each related model is generated once as a named nested model and relations point to it, so cyclic relations give recursive models ($ref in OpenAPI). Relation fields of nested models are optional, the root model keeps the required/optional rules of its own fields. Generated models are cached and their names do not depend on the order of calls (Book, Book_nested, Book_depth2, a selector hash suffix).

Can be used to fully exclude certain fields in fastapi response and requests.

Relations listed in flatten_fields (or all relations with flatten_all) are represented by the related model's primary key (or a list of primary keys for many-to-many and reverse relations) instead of a nested pydantic model, matching the output of model_dump called with the same arguments.

Parameters:

Name Type Description Default
include Union[set, dict, None]

fields of own and nested models to include

None
exclude Union[set, dict, None]

fields of own and nested models to exclude

None
flatten_fields Union[set, list, str, tuple, dict, FieldAccessor, None]

relations to represent as their primary key

None
flatten_all bool

if True every relation is represented as its pk

False
max_depth Optional[int]

number of relation levels to nest at most, None for no limit (cycles become recursive models)

None
omit_back_relations Optional[bool]

leave the relation back to the parent out of nested models (one nested model per (model, relation) pair), False by default (one nested model per model)

None

Raises:

Type Description
QueryDefinitionError

on invalid flatten paths or when a flattened relation has sub-field include/exclude

Source code in ormar/models/mixins/pydantic_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
 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
@classmethod
def get_pydantic(
    cls,
    *,
    include: Union[set, dict, None] = None,
    exclude: Union[set, dict, None] = None,
    flatten_fields: Union[
        set, list, str, tuple, dict, "FieldAccessor", None
    ] = None,
    flatten_all: bool = False,
    max_depth: Optional[int] = None,
    omit_back_relations: Optional[bool] = None,
) -> type[pydantic.BaseModel]:
    """
    Returns a pydantic model out of ormar model.

    Converts also nested ormar models into pydantic models. Each related
    model is generated once as a named nested model and relations point to
    it, so cyclic relations give recursive models (``$ref`` in OpenAPI).
    Relation fields of nested models are optional, the root model keeps
    the required/optional rules of its own fields. Generated models are
    cached and their names do not depend on the order of calls
    (``Book``, ``Book_nested``, ``Book_depth2``, a selector hash suffix).

    Can be used to fully exclude certain fields in fastapi response and requests.

    Relations listed in ``flatten_fields`` (or all relations with
    ``flatten_all``) are represented by the related model's primary key
    (or a list of primary keys for many-to-many and reverse relations)
    instead of a nested pydantic model, matching the output of
    ``model_dump`` called with the same arguments.

    :param include: fields of own and nested models to include
    :type include: Union[set, dict, None]
    :param exclude: fields of own and nested models to exclude
    :type exclude: Union[set, dict, None]
    :param flatten_fields: relations to represent as their primary key
    :type flatten_fields: Union[set, list, str, tuple, dict, FieldAccessor, None]
    :param flatten_all: if True every relation is represented as its pk
    :type flatten_all: bool
    :param max_depth: number of relation levels to nest at most, None for
        no limit (cycles become recursive models)
    :type max_depth: Optional[int]
    :param omit_back_relations: leave the relation back to the parent out
        of nested models (one nested model per (model, relation) pair),
        False by default (one nested model per model)
    :type omit_back_relations: Optional[bool]
    :raises QueryDefinitionError: on invalid flatten paths or when a
        flattened relation has sub-field include/exclude
    """
    flatten_map = resolve_flatten_map(
        model_cls=cast(type["Model"], cls),
        flatten_fields=flatten_fields,
        flatten_all=flatten_all,
    )
    if flatten_map is not None:
        flatten_map.check_vs_selector(normalize_to_dict(include), "include")
        flatten_map.check_vs_selector(normalize_to_dict(exclude), "exclude")

    if (
        instance_traversal_enabled()
        or max_depth is not None
        or omit_back_relations is not None
    ):
        return RecursiveSchemaBuilder(
            omit_back_relations=bool(omit_back_relations)
        ).build(
            model=cls,
            include=include,
            exclude=exclude,
            flatten_map=flatten_map,
            max_depth=max_depth,
        )
    return cls._convert_ormar_to_pydantic(
        include=include,
        exclude=exclude,
        flatten_map=flatten_map,
        relation_map=cls._relation_tree(),
    )

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