Skip to content

ormar

The ormar package is an async mini ORM for Python, with support for Postgres, MySQL, and SQLite.

The main benefit of using ormar are:

  • getting an async ORM that can be used with async frameworks (fastapi, starlette etc.)
  • getting just one model to maintain - you don't have to maintain pydantic and other orm model (sqlalchemy, peewee, gino etc.)

The goal was to create a simple ORM that can be used directly (as request and response models) with fastapi that bases it's data validation on pydantic.

Ormar - apart form obvious ORM in name - get it's name from ormar in swedish which means snakes, and ormar(e) in italian which means cabinet.

And what's a better name for python ORM than snakes cabinet :)

BaseField

Bases: FieldInfo

BaseField serves as a parent class for all basic Fields in ormar. It keeps all common parameters available for all fields as well as set of useful functions.

All values are kept as class variables, ormar Fields are never instantiated. Subclasses pydantic.FieldInfo to keep the fields related to pydantic field types like ConstrainedStr

Source code in ormar/fields/base.py
Python
 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
 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
class BaseField(FieldInfo):  # type: ignore[misc]
    """
    BaseField serves as a parent class for all basic Fields in ormar.
    It keeps all common parameters available for all fields as well as
    set of useful functions.

    All values are kept as class variables, ormar Fields are never instantiated.
    Subclasses pydantic.FieldInfo to keep the fields related
    to pydantic field types like ConstrainedStr
    """

    def __init__(self, **kwargs: Any) -> None:
        self.__type__: type = kwargs.pop("__type__", None)
        self.__pydantic_type__: type = kwargs.pop("__pydantic_type__", None)
        self.__sample__: type = kwargs.pop("__sample__", None)
        self.related_name = kwargs.pop("related_name", None)

        self.column_type: sqlalchemy.Column = kwargs.pop("column_type", None)
        self.name: str = kwargs.pop("name", None)
        self.db_alias: str = kwargs.pop("alias", None)

        self.primary_key: bool = kwargs.pop("primary_key", False)
        self.autoincrement: bool = kwargs.pop("autoincrement", False)
        self.autoincrement_explicit: bool = kwargs.pop("autoincrement_explicit", False)
        self.nullable: bool = kwargs.pop("nullable", False)
        self.sql_nullable: bool = kwargs.pop("sql_nullable", False)
        self.index: bool = kwargs.pop("index", False)
        self.unique: bool = kwargs.pop("unique", False)

        self.one_to_one: bool = kwargs.pop("one_to_one", False)
        self.virtual: bool = kwargs.pop(
            "virtual", None
        )  # ManyToManyFields and reverse ForeignKeyFields
        self.is_multi: bool = kwargs.pop("is_multi", None)  # ManyToManyField
        self.is_relation: bool = kwargs.pop(
            "is_relation", None
        )  # ForeignKeyField + subclasses
        self.is_through: bool = kwargs.pop("is_through", False)  # ThroughFields

        self.through_relation_name = kwargs.pop("through_relation_name", None)
        self.through_reverse_relation_name = kwargs.pop(
            "through_reverse_relation_name", None
        )
        self.through_foreign_key_name: Optional[str] = kwargs.pop(
            "through_foreign_key_name", None
        )
        self.through_reverse_foreign_key_name: Optional[str] = kwargs.pop(
            "through_reverse_foreign_key_name", None
        )
        self.through_relation_nullable: bool = kwargs.pop(
            "through_relation_nullable", True
        )
        self.through_reverse_relation_nullable: bool = kwargs.pop(
            "through_reverse_relation_nullable", True
        )

        self.skip_reverse: bool = kwargs.pop("skip_reverse", False)
        self.skip_field: bool = kwargs.pop("skip_field", False)

        self.owner: type["Model"] = kwargs.pop("owner", None)
        self.to: type["Model"] = kwargs.pop("to", None)
        self.to_key_only: type["Model"] = kwargs.pop("to_key_only", None)
        self.through: type["Model"] = kwargs.pop("through", None)
        self.self_reference: bool = kwargs.pop("self_reference", False)
        self.self_reference_primary: Optional[str] = kwargs.pop(
            "self_reference_primary", None
        )
        self.orders_by: Optional[list[str]] = kwargs.pop("orders_by", None)
        self.related_orders_by: Optional[list[str]] = kwargs.pop(
            "related_orders_by", None
        )

        self.encrypt_secret: str = kwargs.pop("encrypt_secret", None)
        self.encrypt_backend: EncryptBackends = kwargs.pop(
            "encrypt_backend", EncryptBackends.NONE
        )
        self.encrypt_custom_backend: Optional[type[EncryptBackend]] = kwargs.pop(
            "encrypt_custom_backend", None
        )

        self.ormar_default: Any = kwargs.pop("default", None)
        self.server_default: Any = kwargs.pop("server_default", None)
        self.on_update: Any = kwargs.pop("on_update", None)

        self.comment: str = kwargs.pop("comment", None)

        self.represent_as_base64_str: bool = kwargs.pop(
            "represent_as_base64_str", False
        )

        for name, value in kwargs.items():
            setattr(self, name, value)

        kwargs.update(self.get_pydantic_default())
        super().__init__(**kwargs)

    def is_valid_uni_relation(self) -> bool:
        """
        Checks if field is a relation definition but only for ForeignKey relation,
        so excludes ManyToMany fields, as well as virtual ForeignKey
        (second side of FK relation).

        Is used to define if a field is a db ForeignKey column that
        should be saved/populated when dealing with internal/own
        Model columns only.

        :return: result of the check
        :rtype: bool
        """
        return not self.is_multi and not self.virtual

    @property
    def kind(self) -> RelationKind:
        """
        Relation fields override it with the kind they declare.

        :return: ``NOT_A_RELATION`` for plain fields
        :rtype: RelationKind
        """
        return NOT_A_RELATION

    def get_alias(self) -> str:
        """
        Used to translate Model column names to database column names during db queries.

        :return: returns custom database column name if defined by user,
        otherwise field name in ormar/pydantic
        :rtype: str
        """
        return self.db_alias if self.db_alias else self.name

    def get_pydantic_default(self) -> dict:
        """
        Generates base pydantic.FieldInfo with only default and optionally
        required to fix pydantic Json field being set to required=False.
        Used in an ormar Model Metaclass.

        :return: instance of base pydantic.FieldInfo
        :rtype: pydantic.FieldInfo
        """
        base = self.default_value()
        if base is None:
            base = dict(default=None) if self.nullable else dict(default=_Unset)
        return base

    def default_value(self, use_server: bool = False) -> Optional[dict]:
        """
        Returns a FieldInfo instance with populated default
        (static) or default_factory (function).
        If the field is a autoincrement primary key the default is None.
        Otherwise field have to has either default, or default_factory populated.

        If all default conditions fail None is returned.

        Used in converting to pydantic FieldInfo.

        :param use_server: flag marking if server_default should be
        treated as default value, default False
        :type use_server: bool
        :return: returns a call to pydantic.Field
        which is returning a FieldInfo instance
        :rtype: Optional[pydantic.FieldInfo]
        """
        if self.is_auto_primary_key():
            return dict(default=None)
        if self.has_default(use_server=use_server):
            default = (
                self.ormar_default
                if self.ormar_default is not None
                else self.server_default
            )
            if callable(default):
                return dict(default_factory=default)
            return dict(default=default)
        return None

    @overload
    def get_default(
        self,
        *,
        call_default_factory: Literal[True],
        validated_data: Union[dict[str, Any], None] = None,
    ) -> Any: ...

    @overload
    def get_default(self, *, call_default_factory: Literal[False] = ...) -> Any: ...

    def get_default(
        self,
        *,
        call_default_factory: bool = True,
        validated_data: Union[dict[str, Any], None] = None,
        use_server: bool = False,
    ) -> Any:  # noqa CCR001
        """
        Return default value for a field.
        If the field is Callable the function is called and actual result is returned.
        Used to populate default_values for pydantic Model in ormar Model Metaclass.

        :param use_server: flag marking if server_default should be
        treated as default value, default False
        :type use_server: bool
        :return: default value for the field if set, otherwise implicit None
        :rtype: Any
        """
        if self.has_default():
            default = (
                self.ormar_default
                if self.ormar_default is not None
                else self._get_default_server_value(use_server=use_server)
            )
            return self._get_default_callable_value(
                default=default,
                call_default_factory=call_default_factory,
            )

    def _get_default_server_value(self, use_server: bool) -> Any:  # pragma: no cover
        """
        Return default value for a server side if use_server is True
        """
        return self.server_default if use_server else None

    @staticmethod
    def _get_default_callable_value(default: Any, call_default_factory: bool) -> Any:
        """
        Return default factory value if call_default_factory is True
        and default is a callable.
        """
        return default() if (callable(default) and call_default_factory) else default

    def has_default(self, use_server: bool = True) -> bool:
        """
        Checks if the field has default value set.

        :param use_server: flag marking if server_default should be
        treated as default value, default False
        :type use_server: bool
        :return: result of the check if default value is set
        :rtype: bool
        """
        return self.ormar_default is not None or (
            self.server_default is not None and use_server
        )

    def has_on_update(self) -> bool:
        """
        Checks if the field has an on_update value or callable configured.

        :return: result of the check if on_update value is set
        :rtype: bool
        """
        return self.on_update is not None

    def get_on_update(self) -> Any:
        """
        Resolves the on_update value, calling it if it is a callable.

        :return: resolved on_update value
        :rtype: Any
        """
        return self.on_update() if callable(self.on_update) else self.on_update

    def is_auto_primary_key(self) -> bool:
        """
        Checks if field is first a primary key and if it,
        it's than check if it's set to autoincrement.
        Autoincrement primary_key is nullable/optional.

        :return: result of the check for primary key and autoincrement
        :rtype: bool
        """
        if self.primary_key:
            return self.autoincrement
        return False

    def construct_constraints(self) -> list:
        """
        Builds the sqlalchemy ForeignKeys of the field's column. Plain fields
        have none, relation fields build them from their link.

        :return: list of sqlalchemy foreign keys
        :rtype: list[sqlalchemy.schema.ForeignKey]
        """
        return []

    def get_columns(self) -> list[sqlalchemy.Column]:
        """
        :return: the table columns of the field, one for plain fields
        :rtype: list[sqlalchemy.Column]
        """
        return [self.get_column(self.get_alias())]

    def column_aliases(self) -> tuple[str, ...]:
        """
        :return: names of the table columns of the field
        :rtype: tuple[str, ...]
        """
        return (self.get_alias(),)

    def construct_table_constraints(self) -> list:
        """
        :return: table-level constraints of the field, none for plain fields
        :rtype: list
        """
        return []

    def get_column(self, name: str) -> sqlalchemy.Column:
        """
        Returns definition of sqlalchemy.Column used in creation of sqlalchemy.Table.
        Populates name, column type constraints, as well as a number of parameters like
        primary_key, index, unique, nullable, default and server_default.

        :param name: name of the db column - used if alias is not set
        :type name: str
        :return: actual definition of the database column as sqlalchemy requires.
        :rtype: sqlalchemy.Column
        """
        if self.encrypt_backend == EncryptBackends.NONE:
            column: sqlalchemy.Column = sqlalchemy.Column(
                self.db_alias or name,
                self.column_type,
                *self.construct_constraints(),
                primary_key=self.primary_key,
                autoincrement=self.autoincrement,
                nullable=self.sql_nullable,
                index=self.index,
                unique=self.unique,
                default=self.ormar_default,
                server_default=self.server_default,
                comment=self.comment,
            )
        else:
            column = self._get_encrypted_column(name=name)
        return column

    def _get_encrypted_column(self, name: str) -> sqlalchemy.Column:
        """
        Returns EncryptedString column type instead of actual column.

        :param name: column name
        :type name: str
        :return: newly defined column
        :rtype:  sqlalchemy.Column
        """
        if self.primary_key or self.is_relation:
            raise ModelDefinitionError(
                "Primary key field and relations fields cannot be encrypted!"
            )
        column: sqlalchemy.Column = sqlalchemy.Column(
            self.db_alias or name,
            EncryptedString(
                _field_type=self,
                encrypt_secret=self.encrypt_secret,
                encrypt_backend=self.encrypt_backend,
                encrypt_custom_backend=self.encrypt_custom_backend,
            ),
            nullable=self.nullable,
            index=self.index,
            unique=self.unique,
            default=self.ormar_default,
            server_default=self.server_default,
        )
        return column

    def expand_relationship(
        self,
        value: Any,
        child: Union["Model", "NewBaseModel"],
        to_register: bool = True,
    ) -> Any:
        """
        Function overwritten for relations, in basic field the value is returned as is.
        For relations the child model is first constructed (if needed),
        registered in relation and returned.
        For relation fields the value can be a pk value (Any type of field),
        dict (from Model) or actual instance/list of a "Model".

        :param value: a Model field value, returned untouched for non relation fields.
        :type value: Any
        :param child: a child Model to register
        :type child: Union["Model", "NewBaseModel"]
        :param to_register: flag if the relation should be set in RelationshipManager
        :type to_register: bool
        :return: returns untouched value for normal fields, expands only for relations
        :rtype: Any
        """
        return value  # pragma: no cover

    def set_self_reference_flag(self) -> None:
        """
        Sets `self_reference` to True if field to and owner are same model.
        :return: None
        :rtype: None
        """
        if self.owner is not None and (
            self.owner == self.to or self.owner.ormar_config == self.to.ormar_config
        ):
            self.self_reference = True
            self.self_reference_primary = self.name

    def has_unresolved_forward_refs(self) -> bool:
        """
        Verifies if the filed has any ForwardRefs that require updating before the
        model can be used.

        :return: result of the check
        :rtype: bool
        """
        return False

    def evaluate_forward_ref(self, globalns: Any, localns: Any) -> None:
        """
        Evaluates the ForwardRef to actual Field based on global and local namespaces

        :param globalns: global namespace
        :type globalns: Any
        :param localns: local namespace
        :type localns: Any
        :return: None
        :rtype: None
        """

    def get_related_name(self) -> str:
        """
        Returns name to use for reverse relation.
        It's either set as `related_name` or by default it's owner model. get_name + 's'
        :return: name of the related_name or default related name.
        :rtype: str
        """
        return ""  # pragma: no cover

kind property

Relation fields override it with the kind they declare.

Returns:

Type Description
RelationKind

NOT_A_RELATION for plain fields

column_aliases()

Returns:

Type Description
tuple[str, ...]

names of the table columns of the field

Source code in ormar/fields/base.py
Python
311
312
313
314
315
316
def column_aliases(self) -> tuple[str, ...]:
    """
    :return: names of the table columns of the field
    :rtype: tuple[str, ...]
    """
    return (self.get_alias(),)

construct_constraints()

Builds the sqlalchemy ForeignKeys of the field's column. Plain fields have none, relation fields build them from their link.

Returns:

Type Description
list[sqlalchemy.schema.ForeignKey]

list of sqlalchemy foreign keys

Source code in ormar/fields/base.py
Python
294
295
296
297
298
299
300
301
302
def construct_constraints(self) -> list:
    """
    Builds the sqlalchemy ForeignKeys of the field's column. Plain fields
    have none, relation fields build them from their link.

    :return: list of sqlalchemy foreign keys
    :rtype: list[sqlalchemy.schema.ForeignKey]
    """
    return []

construct_table_constraints()

Returns:

Type Description
list

table-level constraints of the field, none for plain fields

Source code in ormar/fields/base.py
Python
318
319
320
321
322
323
def construct_table_constraints(self) -> list:
    """
    :return: table-level constraints of the field, none for plain fields
    :rtype: list
    """
    return []

default_value(use_server=False)

Returns a FieldInfo instance with populated default (static) or default_factory (function). If the field is a autoincrement primary key the default is None. Otherwise field have to has either default, or default_factory populated.

If all default conditions fail None is returned.

Used in converting to pydantic FieldInfo.

Parameters:

Name Type Description Default
use_server bool

flag marking if server_default should be treated as default value, default False

False

Returns:

Type Description
Optional[pydantic.FieldInfo]

returns a call to pydantic.Field which is returning a FieldInfo instance

Source code in ormar/fields/base.py
Python
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
def default_value(self, use_server: bool = False) -> Optional[dict]:
    """
    Returns a FieldInfo instance with populated default
    (static) or default_factory (function).
    If the field is a autoincrement primary key the default is None.
    Otherwise field have to has either default, or default_factory populated.

    If all default conditions fail None is returned.

    Used in converting to pydantic FieldInfo.

    :param use_server: flag marking if server_default should be
    treated as default value, default False
    :type use_server: bool
    :return: returns a call to pydantic.Field
    which is returning a FieldInfo instance
    :rtype: Optional[pydantic.FieldInfo]
    """
    if self.is_auto_primary_key():
        return dict(default=None)
    if self.has_default(use_server=use_server):
        default = (
            self.ormar_default
            if self.ormar_default is not None
            else self.server_default
        )
        if callable(default):
            return dict(default_factory=default)
        return dict(default=default)
    return None

evaluate_forward_ref(globalns, localns)

Evaluates the ForwardRef to actual Field based on global and local namespaces

Parameters:

Name Type Description Default
globalns Any

global namespace

required
localns Any

local namespace

required

Returns:

Type Description
None

None

Source code in ormar/fields/base.py
Python
429
430
431
432
433
434
435
436
437
438
439
def evaluate_forward_ref(self, globalns: Any, localns: Any) -> None:
    """
    Evaluates the ForwardRef to actual Field based on global and local namespaces

    :param globalns: global namespace
    :type globalns: Any
    :param localns: local namespace
    :type localns: Any
    :return: None
    :rtype: None
    """

expand_relationship(value, child, to_register=True)

Function overwritten for relations, in basic field the value is returned as is. For relations the child model is first constructed (if needed), registered in relation and returned. For relation fields the value can be a pk value (Any type of field), dict (from Model) or actual instance/list of a "Model".

Parameters:

Name Type Description Default
value Any

a Model field value, returned untouched for non relation fields.

required
child Union[Model, NewBaseModel]

a child Model to register

required
to_register bool

flag if the relation should be set in RelationshipManager

True

Returns:

Type Description
Any

returns untouched value for normal fields, expands only for relations

Source code in ormar/fields/base.py
Python
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
def expand_relationship(
    self,
    value: Any,
    child: Union["Model", "NewBaseModel"],
    to_register: bool = True,
) -> Any:
    """
    Function overwritten for relations, in basic field the value is returned as is.
    For relations the child model is first constructed (if needed),
    registered in relation and returned.
    For relation fields the value can be a pk value (Any type of field),
    dict (from Model) or actual instance/list of a "Model".

    :param value: a Model field value, returned untouched for non relation fields.
    :type value: Any
    :param child: a child Model to register
    :type child: Union["Model", "NewBaseModel"]
    :param to_register: flag if the relation should be set in RelationshipManager
    :type to_register: bool
    :return: returns untouched value for normal fields, expands only for relations
    :rtype: Any
    """
    return value  # pragma: no cover

get_alias()

Used to translate Model column names to database column names during db queries.

Returns:

Type Description
str

returns custom database column name if defined by user, otherwise field name in ormar/pydantic

Source code in ormar/fields/base.py
Python
140
141
142
143
144
145
146
147
148
def get_alias(self) -> str:
    """
    Used to translate Model column names to database column names during db queries.

    :return: returns custom database column name if defined by user,
    otherwise field name in ormar/pydantic
    :rtype: str
    """
    return self.db_alias if self.db_alias else self.name

get_column(name)

Returns definition of sqlalchemy.Column used in creation of sqlalchemy.Table. Populates name, column type constraints, as well as a number of parameters like primary_key, index, unique, nullable, default and server_default.

Parameters:

Name Type Description Default
name str

name of the db column - used if alias is not set

required

Returns:

Type Description
sqlalchemy.Column

actual definition of the database column as sqlalchemy requires.

Source code in ormar/fields/base.py
Python
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
def get_column(self, name: str) -> sqlalchemy.Column:
    """
    Returns definition of sqlalchemy.Column used in creation of sqlalchemy.Table.
    Populates name, column type constraints, as well as a number of parameters like
    primary_key, index, unique, nullable, default and server_default.

    :param name: name of the db column - used if alias is not set
    :type name: str
    :return: actual definition of the database column as sqlalchemy requires.
    :rtype: sqlalchemy.Column
    """
    if self.encrypt_backend == EncryptBackends.NONE:
        column: sqlalchemy.Column = sqlalchemy.Column(
            self.db_alias or name,
            self.column_type,
            *self.construct_constraints(),
            primary_key=self.primary_key,
            autoincrement=self.autoincrement,
            nullable=self.sql_nullable,
            index=self.index,
            unique=self.unique,
            default=self.ormar_default,
            server_default=self.server_default,
            comment=self.comment,
        )
    else:
        column = self._get_encrypted_column(name=name)
    return column

get_columns()

Returns:

Type Description
list[sqlalchemy.Column]

the table columns of the field, one for plain fields

Source code in ormar/fields/base.py
Python
304
305
306
307
308
309
def get_columns(self) -> list[sqlalchemy.Column]:
    """
    :return: the table columns of the field, one for plain fields
    :rtype: list[sqlalchemy.Column]
    """
    return [self.get_column(self.get_alias())]

get_default(*, call_default_factory=True, validated_data=None, use_server=False)

Python
get_default(
    *,
    call_default_factory: Literal[True],
    validated_data: Union[dict[str, Any], None] = None,
) -> Any
Python
get_default(
    *, call_default_factory: Literal[False] = ...
) -> Any

Return default value for a field. If the field is Callable the function is called and actual result is returned. Used to populate default_values for pydantic Model in ormar Model Metaclass.

Parameters:

Name Type Description Default
use_server bool

flag marking if server_default should be treated as default value, default False

False

Returns:

Type Description
Any

default value for the field if set, otherwise implicit None

Source code in ormar/fields/base.py
Python
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
def get_default(
    self,
    *,
    call_default_factory: bool = True,
    validated_data: Union[dict[str, Any], None] = None,
    use_server: bool = False,
) -> Any:  # noqa CCR001
    """
    Return default value for a field.
    If the field is Callable the function is called and actual result is returned.
    Used to populate default_values for pydantic Model in ormar Model Metaclass.

    :param use_server: flag marking if server_default should be
    treated as default value, default False
    :type use_server: bool
    :return: default value for the field if set, otherwise implicit None
    :rtype: Any
    """
    if self.has_default():
        default = (
            self.ormar_default
            if self.ormar_default is not None
            else self._get_default_server_value(use_server=use_server)
        )
        return self._get_default_callable_value(
            default=default,
            call_default_factory=call_default_factory,
        )

get_on_update()

Resolves the on_update value, calling it if it is a callable.

Returns:

Type Description
Any

resolved on_update value

Source code in ormar/fields/base.py
Python
272
273
274
275
276
277
278
279
def get_on_update(self) -> Any:
    """
    Resolves the on_update value, calling it if it is a callable.

    :return: resolved on_update value
    :rtype: Any
    """
    return self.on_update() if callable(self.on_update) else self.on_update

get_pydantic_default()

Generates base pydantic.FieldInfo with only default and optionally required to fix pydantic Json field being set to required=False. Used in an ormar Model Metaclass.

Returns:

Type Description
pydantic.FieldInfo

instance of base pydantic.FieldInfo

Source code in ormar/fields/base.py
Python
150
151
152
153
154
155
156
157
158
159
160
161
162
def get_pydantic_default(self) -> dict:
    """
    Generates base pydantic.FieldInfo with only default and optionally
    required to fix pydantic Json field being set to required=False.
    Used in an ormar Model Metaclass.

    :return: instance of base pydantic.FieldInfo
    :rtype: pydantic.FieldInfo
    """
    base = self.default_value()
    if base is None:
        base = dict(default=None) if self.nullable else dict(default=_Unset)
    return base

Returns name to use for reverse relation. It's either set as related_name or by default it's owner model. get_name + 's'

Returns:

Type Description
str

name of the related_name or default related name.

Source code in ormar/fields/base.py
Python
441
442
443
444
445
446
447
448
def get_related_name(self) -> str:
    """
    Returns name to use for reverse relation.
    It's either set as `related_name` or by default it's owner model. get_name + 's'
    :return: name of the related_name or default related name.
    :rtype: str
    """
    return ""  # pragma: no cover

has_default(use_server=True)

Checks if the field has default value set.

Parameters:

Name Type Description Default
use_server bool

flag marking if server_default should be treated as default value, default False

True

Returns:

Type Description
bool

result of the check if default value is set

Source code in ormar/fields/base.py
Python
249
250
251
252
253
254
255
256
257
258
259
260
261
def has_default(self, use_server: bool = True) -> bool:
    """
    Checks if the field has default value set.

    :param use_server: flag marking if server_default should be
    treated as default value, default False
    :type use_server: bool
    :return: result of the check if default value is set
    :rtype: bool
    """
    return self.ormar_default is not None or (
        self.server_default is not None and use_server
    )

has_on_update()

Checks if the field has an on_update value or callable configured.

Returns:

Type Description
bool

result of the check if on_update value is set

Source code in ormar/fields/base.py
Python
263
264
265
266
267
268
269
270
def has_on_update(self) -> bool:
    """
    Checks if the field has an on_update value or callable configured.

    :return: result of the check if on_update value is set
    :rtype: bool
    """
    return self.on_update is not None

has_unresolved_forward_refs()

Verifies if the filed has any ForwardRefs that require updating before the model can be used.

Returns:

Type Description
bool

result of the check

Source code in ormar/fields/base.py
Python
419
420
421
422
423
424
425
426
427
def has_unresolved_forward_refs(self) -> bool:
    """
    Verifies if the filed has any ForwardRefs that require updating before the
    model can be used.

    :return: result of the check
    :rtype: bool
    """
    return False

is_auto_primary_key()

Checks if field is first a primary key and if it, it's than check if it's set to autoincrement. Autoincrement primary_key is nullable/optional.

Returns:

Type Description
bool

result of the check for primary key and autoincrement

Source code in ormar/fields/base.py
Python
281
282
283
284
285
286
287
288
289
290
291
292
def is_auto_primary_key(self) -> bool:
    """
    Checks if field is first a primary key and if it,
    it's than check if it's set to autoincrement.
    Autoincrement primary_key is nullable/optional.

    :return: result of the check for primary key and autoincrement
    :rtype: bool
    """
    if self.primary_key:
        return self.autoincrement
    return False

is_valid_uni_relation()

Checks if field is a relation definition but only for ForeignKey relation, so excludes ManyToMany fields, as well as virtual ForeignKey (second side of FK relation).

Is used to define if a field is a db ForeignKey column that should be saved/populated when dealing with internal/own Model columns only.

Returns:

Type Description
bool

result of the check

Source code in ormar/fields/base.py
Python
115
116
117
118
119
120
121
122
123
124
125
126
127
128
def is_valid_uni_relation(self) -> bool:
    """
    Checks if field is a relation definition but only for ForeignKey relation,
    so excludes ManyToMany fields, as well as virtual ForeignKey
    (second side of FK relation).

    Is used to define if a field is a db ForeignKey column that
    should be saved/populated when dealing with internal/own
    Model columns only.

    :return: result of the check
    :rtype: bool
    """
    return not self.is_multi and not self.virtual

set_self_reference_flag()

Sets self_reference to True if field to and owner are same model.

Returns:

Type Description
None

None

Source code in ormar/fields/base.py
Python
407
408
409
410
411
412
413
414
415
416
417
def set_self_reference_flag(self) -> None:
    """
    Sets `self_reference` to True if field to and owner are same model.
    :return: None
    :rtype: None
    """
    if self.owner is not None and (
        self.owner == self.to or self.owner.ormar_config == self.to.ormar_config
    ):
        self.self_reference = True
        self.self_reference_primary = self.name

BigInteger

Bases: Integer, int

BigInteger field factory that construct Field classes and populated their values.

Source code in ormar/fields/model_fields.py
Python
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
class BigInteger(Integer, int):
    """
    BigInteger field factory that construct Field classes and populated their values.
    """

    _type = int
    _sample = 0

    @classmethod
    def get_column_type(cls, **kwargs: Any) -> Any:
        """
        Return proper type of db column for given field type.
        Accepts required and optional parameters that each column type accepts.

        :param kwargs: key, value pairs of sqlalchemy options
        :type kwargs: Any
        :return: initialized column with proper options
        :rtype: sqlalchemy Column
        """
        return unsigned_on_mysql(
            sqlalchemy.BigInteger(), mysql.BIGINT, kwargs.get("unsigned", False)
        )

get_column_type(**kwargs) classmethod

Return proper type of db column for given field type. Accepts required and optional parameters that each column type accepts.

Parameters:

Name Type Description Default
kwargs Any

key, value pairs of sqlalchemy options

{}

Returns:

Type Description
sqlalchemy Column

initialized column with proper options

Source code in ormar/fields/model_fields.py
Python
600
601
602
603
604
605
606
607
608
609
610
611
612
613
@classmethod
def get_column_type(cls, **kwargs: Any) -> Any:
    """
    Return proper type of db column for given field type.
    Accepts required and optional parameters that each column type accepts.

    :param kwargs: key, value pairs of sqlalchemy options
    :type kwargs: Any
    :return: initialized column with proper options
    :rtype: sqlalchemy Column
    """
    return unsigned_on_mysql(
        sqlalchemy.BigInteger(), mysql.BIGINT, kwargs.get("unsigned", False)
    )

Boolean

Bases: ModelFieldFactory, int

Boolean field factory that construct Field classes and populated their values.

Source code in ormar/fields/model_fields.py
Python
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
class Boolean(ModelFieldFactory, int):
    """
    Boolean field factory that construct Field classes and populated their values.
    """

    _type = bool
    _sample = True

    @classmethod
    def get_column_type(cls, **kwargs: Any) -> Any:
        """
        Return proper type of db column for given field type.
        Accepts required and optional parameters that each column type accepts.

        :param kwargs: key, value pairs of sqlalchemy options
        :type kwargs: Any
        :return: initialized column with proper options
        :rtype: sqlalchemy Column
        """
        return sqlalchemy.Boolean()

get_column_type(**kwargs) classmethod

Return proper type of db column for given field type. Accepts required and optional parameters that each column type accepts.

Parameters:

Name Type Description Default
kwargs Any

key, value pairs of sqlalchemy options

{}

Returns:

Type Description
sqlalchemy Column

initialized column with proper options

Source code in ormar/fields/model_fields.py
Python
415
416
417
418
419
420
421
422
423
424
425
426
@classmethod
def get_column_type(cls, **kwargs: Any) -> Any:
    """
    Return proper type of db column for given field type.
    Accepts required and optional parameters that each column type accepts.

    :param kwargs: key, value pairs of sqlalchemy options
    :type kwargs: Any
    :return: initialized column with proper options
    :rtype: sqlalchemy Column
    """
    return sqlalchemy.Boolean()

CheckColumns

Bases: CheckConstraint

Subclass of sqlalchemy.CheckConstraint. Used to avoid importing anything from sqlalchemy by user.

Note that some databases do not actively support check constraints such as MySQL.

Source code in ormar/fields/constraints.py
Python
49
50
51
52
53
54
55
class CheckColumns(CheckConstraint):
    """
    Subclass of sqlalchemy.CheckConstraint.
    Used to avoid importing anything from sqlalchemy by user.

    Note that some databases do not actively support check constraints such as MySQL.
    """

Coalesce

Bases: Function

The first argument that is not NULL.

Source code in ormar/queryset/expressions.py
Python
185
186
187
188
class Coalesce(Function):
    """The first argument that is not ``NULL``."""

    _sql_name = "coalesce"

DatabaseConnection

Wrapper around SQLAlchemy AsyncEngine that provides a databases-compatible API.

Source code in ormar/databases/connection.py
Python
 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
class DatabaseConnection:
    """
    Wrapper around SQLAlchemy AsyncEngine that provides a databases-compatible API.
    """

    def __init__(self, url: str, native_execution: bool = True, **options: Any) -> None:
        """
        Initialize database connection.

        :param url: Database URL with an async driver (e.g., postgresql+asyncpg://)
        :param native_execution: run statements directly on the driver for
            asyncpg, asyncmy and aiosqlite instead of through SQLAlchemy's
            execution layer
        :param options: Additional engine options passed to
            ``create_async_engine``; ``pool_size`` defaults to 10 and
            ``max_overflow`` to 10. ``min_connections`` (default
            ``pool_size``) opens that many pooled connections on
            ``connect()`` (at most ``pool_size``), so the first concurrent
            queries do not wait for new connections; 0 keeps the pool lazy.
            ``json_serializer`` and ``json_deserializer`` of JSON columns
            default to orjson.
        """
        self._force_rollback = options.pop("force_rollback", False)
        self._url = url
        # Set reasonable pool defaults if not provided; overflow connections are
        # closed on checkin, so pool_size should cover the usual concurrency
        if "pool_size" not in options:
            options["pool_size"] = 10
        if "max_overflow" not in options:
            options["max_overflow"] = 10
        options.setdefault("json_serializer", serialize_json_column)
        options.setdefault("json_deserializer", deserialize_json_column)
        self._min_connections = options.pop("min_connections", options["pool_size"])
        self._options = options
        self._engine: Optional[AsyncEngine] = None
        self._autocommit_engine: Optional[AsyncEngine] = None
        self.rules: DialectRules = rules_for(
            backend_name=make_url(url).get_backend_name()
        )
        self._autocommit_by_default = (
            "isolation_level" not in options and self.rules.autocommit_engine
        )

        self._global_transaction: Optional[Transaction] = None
        self._native_execution = native_execution
        self.native_backend: Optional[NativeBackend] = None

    async def connect(self) -> None:
        """Connect to the database by creating the async engine."""
        if self._engine is None:
            engine_options = (
                {**self._options, "isolation_level": "AUTOCOMMIT"}
                if self._autocommit_by_default
                else self._options
            )
            self._engine = create_async_engine(self._url, **engine_options)
            # Engine (or a view of the same engine/pool) in AUTOCOMMIT mode.
            # Standalone queries use this to avoid a BEGIN/COMMIT round-trip
            # per call, matching legacy `databases`-library semantics. Explicit
            # Transactions keep using ``self._engine`` so BEGIN / SAVEPOINT
            # still work.
            self._autocommit_engine = (
                self._engine
                if self._autocommit_by_default
                else self._engine.execution_options(isolation_level="AUTOCOMMIT")
            )

            self.native_backend = build_native_backend(
                dialect=self._engine.dialect, enabled=self._native_execution
            )

            # Set up SQLite foreign keys pragma if using SQLite
            if self.rules.foreign_keys_pragma:  # pragma: nocover

                @event.listens_for(self._engine.sync_engine, "connect")
                def set_sqlite_pragma(dbapi_conn: Any, connection_record: Any) -> None:
                    cursor = dbapi_conn.cursor()
                    cursor.execute("PRAGMA foreign_keys=ON")
                    cursor.close()

            await self._open_min_connections()

            if self._force_rollback:
                assert self._global_transaction is None
                self._global_transaction = Transaction(
                    self, force_rollback=self._force_rollback
                )
                await self._global_transaction.__aenter__()

    async def _open_min_connections(self) -> None:
        """
        Open ``min_connections`` pooled connections at once and return them to
        the pool, capped at the pool size (connections beyond it are closed
        when returned).
        """
        assert self._engine is not None
        count = min(self._min_connections, self._options["pool_size"])
        if count > 0:
            async with AsyncExitStack() as stack:
                await asyncio.gather(
                    *(
                        stack.enter_async_context(self._engine.connect())
                        for _ in range(count)
                    )
                )

    async def disconnect(self) -> None:
        """
        Disconnect from the database and dispose of the engine.
        In case of force_rollback, also roll back the global transaction.
        """
        if self._engine is not None:
            if self._force_rollback:
                assert self._global_transaction is not None
                await self._global_transaction.__aexit__()
                self._global_transaction = None

            await self._engine.dispose()
            self._engine = None
            self._autocommit_engine = None
            self.native_backend = None

    @property
    def is_connected(self) -> bool:
        """Check if the engine is connected."""
        return self._engine is not None

    @property
    def engine(self) -> AsyncEngine:
        """Get the async engine."""
        assert self._engine is not None, "DatabaseConnection not connected"
        return self._engine

    @property
    def dialect(self) -> Any:
        """Get the database dialect."""
        return self.engine.dialect

    @property
    def url(self) -> str:
        """Get the database URL."""
        return self._url

    @asynccontextmanager
    async def connection(self) -> AsyncIterator[AsyncConnection]:
        """
        Get a connection from the pool.
        If inside a transaction, returns the transaction connection.
        """
        trans_conn = _transaction_connection.get()
        if trans_conn is not None:
            yield trans_conn
        else:
            async with self.engine.connect() as conn:
                await self.restore_transaction_isolation(conn)
                yield conn

    async def restore_transaction_isolation(self, conn: AsyncConnection) -> None:
        """
        Switch a freshly checked out connection to the server's default isolation
        level when the engine runs in AUTOCOMMIT, so explicit transactions get
        a real BEGIN / COMMIT. The pool resets it back to AUTOCOMMIT on checkin.

        :param conn: connection checked out from the main engine
        :type conn: AsyncConnection
        """
        if self._autocommit_by_default:  # pragma: no cover
            await conn.execution_options(
                isolation_level=conn.dialect.default_isolation_level
            )

    def transaction(self, force_rollback: bool = False) -> Transaction:
        """
        Create a transaction context manager.

        :param force_rollback: If True, always rollback (used for testing)
        """
        return Transaction(self, force_rollback=force_rollback)

    @asynccontextmanager
    async def get_query_executor(
        self, *, transactional: bool = False
    ) -> AsyncIterator[QueryExecutor]:
        """
        Get connection, reusing transaction connection if in transaction.

        :param transactional: If True, open an explicit transaction for the
            scope of the executor. Use for server-side cursors (``iterate``)
            and multi-row ``execute_many`` batches, which need a real
            transaction either because AUTOCOMMIT would commit each row
            separately or because the driver (asyncpg) requires a
            transaction for streaming.
        :type transactional: bool
        :return: QueryExecutor wrapping a connection
        :rtype: QueryExecutor
        """
        trans_conn = self.get_transaction_connection()
        if trans_conn is not None:
            # Inside a transaction - reuse the transaction's connection
            yield QueryExecutor(connection=trans_conn, native=self.native_backend)
        elif transactional:
            async with self.transaction():
                conn = self.get_transaction_connection()
                assert conn is not None
                yield QueryExecutor(connection=conn, native=self.native_backend)
        else:
            # Outside transaction: use AUTOCOMMIT view so each statement
            # commits at the driver level with no extra BEGIN/COMMIT
            # round-trip.
            assert self._autocommit_engine is not None
            async with self._autocommit_engine.connect() as conn:
                yield QueryExecutor(connection=conn, native=self.native_backend)

    @property
    def atomic_execute_many(self) -> bool:
        """
        Whether ``execute_many`` outside a transaction is atomic on its own
        (native asyncpg), so a single batch needs no explicit transaction.

        ``bulk_create`` uses it to skip ``BEGIN``/``COMMIT`` around a lone
        ``executemany``: on asyncpg a failing row already leaves no rows
        inserted. Other drivers give no such guarantee, so a batch there
        still runs in a transaction.

        :return: True when a lone batch needs no transaction
        :rtype: bool
        """
        return (
            self.native_backend is not None
            and self.native_backend.adapter.atomic_execute_many
        )

    async def start_driver_transaction(self, connection: AsyncConnection) -> None:
        """
        Make sure the driver-level transaction is open on a connection
        SQLAlchemy began a transaction on, so natively executed statements
        run inside it.

        :param connection: connection with a begun transaction
        :type connection: AsyncConnection
        """
        if self.native_backend is not None:
            await self.native_backend.adapter.start_transaction(
                sa_connection=connection
            )

    def get_transaction_connection(self) -> Optional[AsyncConnection]:
        """Get the current transaction connection if in a transaction."""
        return _transaction_connection.get()

    def set_transaction_connection(self, conn: Optional[AsyncConnection]) -> None:
        """Set the current transaction connection."""
        _transaction_connection.set(conn)

    async def __aenter__(self) -> "DatabaseConnection":
        """Async context manager entry - connect to a database."""
        await self.connect()
        return self

    async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
        """Async context manager exit - disconnect from database."""
        await self.disconnect()

atomic_execute_many property

Whether execute_many outside a transaction is atomic on its own (native asyncpg), so a single batch needs no explicit transaction.

bulk_create uses it to skip BEGIN/COMMIT around a lone executemany: on asyncpg a failing row already leaves no rows inserted. Other drivers give no such guarantee, so a batch there still runs in a transaction.

Returns:

Type Description
bool

True when a lone batch needs no transaction

dialect property

Get the database dialect.

engine property

Get the async engine.

is_connected property

Check if the engine is connected.

url property

Get the database URL.

__aenter__() async

Async context manager entry - connect to a database.

Source code in ormar/databases/connection.py
Python
282
283
284
285
async def __aenter__(self) -> "DatabaseConnection":
    """Async context manager entry - connect to a database."""
    await self.connect()
    return self

__aexit__(exc_type, exc_val, exc_tb) async

Async context manager exit - disconnect from database.

Source code in ormar/databases/connection.py
Python
287
288
289
async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
    """Async context manager exit - disconnect from database."""
    await self.disconnect()

__init__(url, native_execution=True, **options)

Initialize database connection.

Parameters:

Name Type Description Default
url str

Database URL with an async driver (e.g., postgresql+asyncpg://)

required
native_execution bool

run statements directly on the driver for asyncpg, asyncmy and aiosqlite instead of through SQLAlchemy's execution layer

True
options Any

Additional engine options passed to create_async_engine; pool_size defaults to 10 and max_overflow to 10. min_connections (default pool_size) opens that many pooled connections on connect() (at most pool_size), so the first concurrent queries do not wait for new connections; 0 keeps the pool lazy. json_serializer and json_deserializer of JSON columns default to orjson.

{}
Source code in ormar/databases/connection.py
Python
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
def __init__(self, url: str, native_execution: bool = True, **options: Any) -> None:
    """
    Initialize database connection.

    :param url: Database URL with an async driver (e.g., postgresql+asyncpg://)
    :param native_execution: run statements directly on the driver for
        asyncpg, asyncmy and aiosqlite instead of through SQLAlchemy's
        execution layer
    :param options: Additional engine options passed to
        ``create_async_engine``; ``pool_size`` defaults to 10 and
        ``max_overflow`` to 10. ``min_connections`` (default
        ``pool_size``) opens that many pooled connections on
        ``connect()`` (at most ``pool_size``), so the first concurrent
        queries do not wait for new connections; 0 keeps the pool lazy.
        ``json_serializer`` and ``json_deserializer`` of JSON columns
        default to orjson.
    """
    self._force_rollback = options.pop("force_rollback", False)
    self._url = url
    # Set reasonable pool defaults if not provided; overflow connections are
    # closed on checkin, so pool_size should cover the usual concurrency
    if "pool_size" not in options:
        options["pool_size"] = 10
    if "max_overflow" not in options:
        options["max_overflow"] = 10
    options.setdefault("json_serializer", serialize_json_column)
    options.setdefault("json_deserializer", deserialize_json_column)
    self._min_connections = options.pop("min_connections", options["pool_size"])
    self._options = options
    self._engine: Optional[AsyncEngine] = None
    self._autocommit_engine: Optional[AsyncEngine] = None
    self.rules: DialectRules = rules_for(
        backend_name=make_url(url).get_backend_name()
    )
    self._autocommit_by_default = (
        "isolation_level" not in options and self.rules.autocommit_engine
    )

    self._global_transaction: Optional[Transaction] = None
    self._native_execution = native_execution
    self.native_backend: Optional[NativeBackend] = None

connect() async

Connect to the database by creating the async engine.

Source code in ormar/databases/connection.py
Python
 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
async def connect(self) -> None:
    """Connect to the database by creating the async engine."""
    if self._engine is None:
        engine_options = (
            {**self._options, "isolation_level": "AUTOCOMMIT"}
            if self._autocommit_by_default
            else self._options
        )
        self._engine = create_async_engine(self._url, **engine_options)
        # Engine (or a view of the same engine/pool) in AUTOCOMMIT mode.
        # Standalone queries use this to avoid a BEGIN/COMMIT round-trip
        # per call, matching legacy `databases`-library semantics. Explicit
        # Transactions keep using ``self._engine`` so BEGIN / SAVEPOINT
        # still work.
        self._autocommit_engine = (
            self._engine
            if self._autocommit_by_default
            else self._engine.execution_options(isolation_level="AUTOCOMMIT")
        )

        self.native_backend = build_native_backend(
            dialect=self._engine.dialect, enabled=self._native_execution
        )

        # Set up SQLite foreign keys pragma if using SQLite
        if self.rules.foreign_keys_pragma:  # pragma: nocover

            @event.listens_for(self._engine.sync_engine, "connect")
            def set_sqlite_pragma(dbapi_conn: Any, connection_record: Any) -> None:
                cursor = dbapi_conn.cursor()
                cursor.execute("PRAGMA foreign_keys=ON")
                cursor.close()

        await self._open_min_connections()

        if self._force_rollback:
            assert self._global_transaction is None
            self._global_transaction = Transaction(
                self, force_rollback=self._force_rollback
            )
            await self._global_transaction.__aenter__()

connection() async

Get a connection from the pool. If inside a transaction, returns the transaction connection.

Source code in ormar/databases/connection.py
Python
171
172
173
174
175
176
177
178
179
180
181
182
183
@asynccontextmanager
async def connection(self) -> AsyncIterator[AsyncConnection]:
    """
    Get a connection from the pool.
    If inside a transaction, returns the transaction connection.
    """
    trans_conn = _transaction_connection.get()
    if trans_conn is not None:
        yield trans_conn
    else:
        async with self.engine.connect() as conn:
            await self.restore_transaction_isolation(conn)
            yield conn

disconnect() async

Disconnect from the database and dispose of the engine. In case of force_rollback, also roll back the global transaction.

Source code in ormar/databases/connection.py
Python
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
async def disconnect(self) -> None:
    """
    Disconnect from the database and dispose of the engine.
    In case of force_rollback, also roll back the global transaction.
    """
    if self._engine is not None:
        if self._force_rollback:
            assert self._global_transaction is not None
            await self._global_transaction.__aexit__()
            self._global_transaction = None

        await self._engine.dispose()
        self._engine = None
        self._autocommit_engine = None
        self.native_backend = None

get_query_executor(*, transactional=False) async

Get connection, reusing transaction connection if in transaction.

Parameters:

Name Type Description Default
transactional bool

If True, open an explicit transaction for the scope of the executor. Use for server-side cursors (iterate) and multi-row execute_many batches, which need a real transaction either because AUTOCOMMIT would commit each row separately or because the driver (asyncpg) requires a transaction for streaming.

False

Returns:

Type Description
QueryExecutor

QueryExecutor wrapping a connection

Source code in ormar/databases/connection.py
Python
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
@asynccontextmanager
async def get_query_executor(
    self, *, transactional: bool = False
) -> AsyncIterator[QueryExecutor]:
    """
    Get connection, reusing transaction connection if in transaction.

    :param transactional: If True, open an explicit transaction for the
        scope of the executor. Use for server-side cursors (``iterate``)
        and multi-row ``execute_many`` batches, which need a real
        transaction either because AUTOCOMMIT would commit each row
        separately or because the driver (asyncpg) requires a
        transaction for streaming.
    :type transactional: bool
    :return: QueryExecutor wrapping a connection
    :rtype: QueryExecutor
    """
    trans_conn = self.get_transaction_connection()
    if trans_conn is not None:
        # Inside a transaction - reuse the transaction's connection
        yield QueryExecutor(connection=trans_conn, native=self.native_backend)
    elif transactional:
        async with self.transaction():
            conn = self.get_transaction_connection()
            assert conn is not None
            yield QueryExecutor(connection=conn, native=self.native_backend)
    else:
        # Outside transaction: use AUTOCOMMIT view so each statement
        # commits at the driver level with no extra BEGIN/COMMIT
        # round-trip.
        assert self._autocommit_engine is not None
        async with self._autocommit_engine.connect() as conn:
            yield QueryExecutor(connection=conn, native=self.native_backend)

get_transaction_connection()

Get the current transaction connection if in a transaction.

Source code in ormar/databases/connection.py
Python
274
275
276
def get_transaction_connection(self) -> Optional[AsyncConnection]:
    """Get the current transaction connection if in a transaction."""
    return _transaction_connection.get()

restore_transaction_isolation(conn) async

Switch a freshly checked out connection to the server's default isolation level when the engine runs in AUTOCOMMIT, so explicit transactions get a real BEGIN / COMMIT. The pool resets it back to AUTOCOMMIT on checkin.

Parameters:

Name Type Description Default
conn AsyncConnection

connection checked out from the main engine

required
Source code in ormar/databases/connection.py
Python
185
186
187
188
189
190
191
192
193
194
195
196
197
async def restore_transaction_isolation(self, conn: AsyncConnection) -> None:
    """
    Switch a freshly checked out connection to the server's default isolation
    level when the engine runs in AUTOCOMMIT, so explicit transactions get
    a real BEGIN / COMMIT. The pool resets it back to AUTOCOMMIT on checkin.

    :param conn: connection checked out from the main engine
    :type conn: AsyncConnection
    """
    if self._autocommit_by_default:  # pragma: no cover
        await conn.execution_options(
            isolation_level=conn.dialect.default_isolation_level
        )

set_transaction_connection(conn)

Set the current transaction connection.

Source code in ormar/databases/connection.py
Python
278
279
280
def set_transaction_connection(self, conn: Optional[AsyncConnection]) -> None:
    """Set the current transaction connection."""
    _transaction_connection.set(conn)

start_driver_transaction(connection) async

Make sure the driver-level transaction is open on a connection SQLAlchemy began a transaction on, so natively executed statements run inside it.

Parameters:

Name Type Description Default
connection AsyncConnection

connection with a begun transaction

required
Source code in ormar/databases/connection.py
Python
260
261
262
263
264
265
266
267
268
269
270
271
272
async def start_driver_transaction(self, connection: AsyncConnection) -> None:
    """
    Make sure the driver-level transaction is open on a connection
    SQLAlchemy began a transaction on, so natively executed statements
    run inside it.

    :param connection: connection with a begun transaction
    :type connection: AsyncConnection
    """
    if self.native_backend is not None:
        await self.native_backend.adapter.start_transaction(
            sa_connection=connection
        )

transaction(force_rollback=False)

Create a transaction context manager.

Parameters:

Name Type Description Default
force_rollback bool

If True, always rollback (used for testing)

False
Source code in ormar/databases/connection.py
Python
199
200
201
202
203
204
205
def transaction(self, force_rollback: bool = False) -> Transaction:
    """
    Create a transaction context manager.

    :param force_rollback: If True, always rollback (used for testing)
    """
    return Transaction(self, force_rollback=force_rollback)

Date

Bases: ModelFieldFactory, date

Date field factory that construct Field classes and populated their values.

Source code in ormar/fields/model_fields.py
Python
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
class Date(ModelFieldFactory, datetime.date):
    """
    Date field factory that construct Field classes and populated their values.
    """

    _type = datetime.date
    _sample = "date"

    @classmethod
    def get_column_type(cls, **kwargs: Any) -> Any:
        """
        Return proper type of db column for given field type.
        Accepts required and optional parameters that each column type accepts.

        :param kwargs: key, value pairs of sqlalchemy options
        :type kwargs: Any
        :return: initialized column with proper options
        :rtype: sqlalchemy Column
        """
        return sqlalchemy.Date()

get_column_type(**kwargs) classmethod

Return proper type of db column for given field type. Accepts required and optional parameters that each column type accepts.

Parameters:

Name Type Description Default
kwargs Any

key, value pairs of sqlalchemy options

{}

Returns:

Type Description
sqlalchemy Column

initialized column with proper options

Source code in ormar/fields/model_fields.py
Python
472
473
474
475
476
477
478
479
480
481
482
483
@classmethod
def get_column_type(cls, **kwargs: Any) -> Any:
    """
    Return proper type of db column for given field type.
    Accepts required and optional parameters that each column type accepts.

    :param kwargs: key, value pairs of sqlalchemy options
    :type kwargs: Any
    :return: initialized column with proper options
    :rtype: sqlalchemy Column
    """
    return sqlalchemy.Date()

DateTime

Bases: ModelFieldFactory, datetime

DateTime field factory that construct Field classes and populated their values.

Source code in ormar/fields/model_fields.py
Python
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
class DateTime(ModelFieldFactory, datetime.datetime):
    """
    DateTime field factory that construct Field classes and populated their values.
    """

    _type = datetime.datetime
    _sample = "datetime"

    def __new__(  # type: ignore # noqa CFQ002
        cls, *, timezone: bool = False, **kwargs: Any
    ) -> Self:  # type: ignore
        kwargs = {
            **kwargs,
            **{
                k: v
                for k, v in locals().items()
                if k not in ["cls", "__class__", "kwargs"]
            },
        }
        return super().__new__(cls, **kwargs)

    @classmethod
    def get_column_type(cls, **kwargs: Any) -> Any:
        """
        Return proper type of db column for given field type.
        Accepts required and optional parameters that each column type accepts.

        :param kwargs: key, value pairs of sqlalchemy options
        :type kwargs: Any
        :return: initialized column with proper options
        :rtype: sqlalchemy Column
        """
        return sqlalchemy.DateTime(timezone=kwargs.get("timezone", False))

get_column_type(**kwargs) classmethod

Return proper type of db column for given field type. Accepts required and optional parameters that each column type accepts.

Parameters:

Name Type Description Default
kwargs Any

key, value pairs of sqlalchemy options

{}

Returns:

Type Description
sqlalchemy Column

initialized column with proper options

Source code in ormar/fields/model_fields.py
Python
450
451
452
453
454
455
456
457
458
459
460
461
@classmethod
def get_column_type(cls, **kwargs: Any) -> Any:
    """
    Return proper type of db column for given field type.
    Accepts required and optional parameters that each column type accepts.

    :param kwargs: key, value pairs of sqlalchemy options
    :type kwargs: Any
    :return: initialized column with proper options
    :rtype: sqlalchemy Column
    """
    return sqlalchemy.DateTime(timezone=kwargs.get("timezone", False))

Decimal

Bases: ModelFieldFactory, Decimal

Decimal field factory that construct Field classes and populated their values.

Source code in ormar/fields/model_fields.py
Python
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
class Decimal(ModelFieldFactory, decimal.Decimal):
    """
    Decimal field factory that construct Field classes and populated their values.
    """

    _type = decimal.Decimal
    _sample = 0.0

    def __new__(  # type: ignore # noqa CFQ002
        cls,
        *,
        minimum: Optional[float] = None,
        maximum: Optional[float] = None,
        multiple_of: Optional[int] = None,
        precision: Optional[int] = None,
        scale: Optional[int] = None,
        max_digits: Optional[int] = None,
        decimal_places: Optional[int] = None,
        **kwargs: Any,
    ) -> Self:
        kwargs = {
            **kwargs,
            **{
                k: v
                for k, v in locals().items()
                if k not in ["cls", "__class__", "kwargs"]
            },
        }
        kwargs["ge"] = kwargs["minimum"]
        kwargs["le"] = kwargs["maximum"]

        if kwargs.get("max_digits"):
            kwargs["precision"] = kwargs["max_digits"]
        elif kwargs.get("precision"):
            kwargs["max_digits"] = kwargs["precision"]

        if kwargs.get("decimal_places"):
            kwargs["scale"] = kwargs["decimal_places"]
        elif kwargs.get("scale"):
            kwargs["decimal_places"] = kwargs["scale"]

        return super().__new__(cls, **kwargs)

    @classmethod
    def get_column_type(cls, **kwargs: Any) -> Any:
        """
        Return proper type of db column for given field type.
        Accepts required and optional parameters that each column type accepts.

        :param kwargs: key, value pairs of sqlalchemy options
        :type kwargs: Any
        :return: initialized column with proper options
        :rtype: sqlalchemy Column
        """
        precision = kwargs.get("precision")
        scale = kwargs.get("scale")
        return sqlalchemy.DECIMAL(precision=precision, scale=scale)

    @classmethod
    def validate(cls, **kwargs: Any) -> None:
        """
        Used to validate if all required parameters on a given field type are set.
        :param kwargs: all params passed during construction
        :type kwargs: Any
        """
        precision = kwargs.get("precision")
        scale = kwargs.get("scale")
        if precision is None or precision < 0 or scale is None or scale < 0:
            raise ModelDefinitionError(
                "Parameters scale and precision are required for field Decimal"
            )

get_column_type(**kwargs) classmethod

Return proper type of db column for given field type. Accepts required and optional parameters that each column type accepts.

Parameters:

Name Type Description Default
kwargs Any

key, value pairs of sqlalchemy options

{}

Returns:

Type Description
sqlalchemy Column

initialized column with proper options

Source code in ormar/fields/model_fields.py
Python
683
684
685
686
687
688
689
690
691
692
693
694
695
696
@classmethod
def get_column_type(cls, **kwargs: Any) -> Any:
    """
    Return proper type of db column for given field type.
    Accepts required and optional parameters that each column type accepts.

    :param kwargs: key, value pairs of sqlalchemy options
    :type kwargs: Any
    :return: initialized column with proper options
    :rtype: sqlalchemy Column
    """
    precision = kwargs.get("precision")
    scale = kwargs.get("scale")
    return sqlalchemy.DECIMAL(precision=precision, scale=scale)

validate(**kwargs) classmethod

Used to validate if all required parameters on a given field type are set.

Parameters:

Name Type Description Default
kwargs Any

all params passed during construction

{}
Source code in ormar/fields/model_fields.py
Python
698
699
700
701
702
703
704
705
706
707
708
709
710
@classmethod
def validate(cls, **kwargs: Any) -> None:
    """
    Used to validate if all required parameters on a given field type are set.
    :param kwargs: all params passed during construction
    :type kwargs: Any
    """
    precision = kwargs.get("precision")
    scale = kwargs.get("scale")
    if precision is None or precision < 0 or scale is None or scale < 0:
        raise ModelDefinitionError(
            "Parameters scale and precision are required for field Decimal"
        )

Enum

Bases: ModelFieldFactory

Enum field factory that construct Field classes and populated their values.

Source code in ormar/fields/model_fields.py
Python
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
class Enum(ModelFieldFactory):
    """
    Enum field factory that construct Field classes and populated their values.
    """

    _type = E
    _sample = None

    def __new__(  # type: ignore # noqa CFQ002
        cls, *, enum_class: type[E], store_values: bool = False, **kwargs: Any
    ) -> Self:
        kwargs = {
            **kwargs,
            **{
                k: v
                for k, v in locals().items()
                if k not in ["cls", "__class__", "kwargs"]
            },
        }
        return super().__new__(cls, **kwargs)

    @classmethod
    def validate(cls, **kwargs: Any) -> None:
        enum_class = kwargs.get("enum_class")
        if enum_class is None or not isinstance(enum_class, EnumMeta):
            raise ModelDefinitionError("Enum Field choices must be EnumType")
        if kwargs.get("store_values") and kwargs.get("values_callable"):
            raise ModelDefinitionError(
                "Enum Field accepts store_values or values_callable, not both"
            )

    @classmethod
    def get_column_type(cls, **kwargs: Any) -> Any:
        """
        Return the column type of the enum.

        SQLAlchemy Enum options, such as ``values_callable``, are forwarded
        so callers can store enum values instead of enum names.

        With ``store_values=True`` the column stores member values: an ``int``
        enum gets an ``INTEGER`` column (see ``IntegerEnum``), any other enum
        a ``sqlalchemy.Enum`` of its values as strings.
        """
        enum_cls = kwargs.get("enum_class")
        if kwargs.get("store_values") and issubclass(enum_cls, int):
            return IntegerEnum(enum_cls)
        enum_kwargs = {
            key: value
            for key, value in kwargs.items()
            if key in _SQLALCHEMY_ENUM_KWARGS
        }
        if kwargs.get("store_values"):
            enum_kwargs["values_callable"] = lambda enum: [
                str(member.value) for member in enum
            ]
        return sqlalchemy.Enum(enum_cls, **enum_kwargs)

get_column_type(**kwargs) classmethod

Return the column type of the enum.

SQLAlchemy Enum options, such as values_callable, are forwarded so callers can store enum values instead of enum names.

With store_values=True the column stores member values: an int enum gets an INTEGER column (see IntegerEnum), any other enum a sqlalchemy.Enum of its values as strings.

Source code in ormar/fields/model_fields.py
Python
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
@classmethod
def get_column_type(cls, **kwargs: Any) -> Any:
    """
    Return the column type of the enum.

    SQLAlchemy Enum options, such as ``values_callable``, are forwarded
    so callers can store enum values instead of enum names.

    With ``store_values=True`` the column stores member values: an ``int``
    enum gets an ``INTEGER`` column (see ``IntegerEnum``), any other enum
    a ``sqlalchemy.Enum`` of its values as strings.
    """
    enum_cls = kwargs.get("enum_class")
    if kwargs.get("store_values") and issubclass(enum_cls, int):
        return IntegerEnum(enum_cls)
    enum_kwargs = {
        key: value
        for key, value in kwargs.items()
        if key in _SQLALCHEMY_ENUM_KWARGS
    }
    if kwargs.get("store_values"):
        enum_kwargs["values_callable"] = lambda enum: [
            str(member.value) for member in enum
        ]
    return sqlalchemy.Enum(enum_cls, **enum_kwargs)

ExcludableItems

Keeps a dictionary of Excludables by alias + model_name keys to allow quick lookup by nested models without need to travers deeply nested dictionaries and passing include/exclude around.

Source code in ormar/models/excludable.py
Python
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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
class ExcludableItems:
    """
    Keeps a dictionary of Excludables by alias + model_name keys
    to allow quick lookup by nested models without need to travers
    deeply nested dictionaries and passing include/exclude around.
    """

    def __init__(self) -> None:
        self.items: dict[str, Excludable] = dict()
        self._flatten_paths: set[PathParts] = set()
        self._flatten_map_cache: Optional[FlattenMap] = None
        self._included_relation_paths: set[PathParts] = set()

    @classmethod
    def from_excludable(cls, other: "ExcludableItems") -> "ExcludableItems":
        """
        Copy passed ExcludableItems to avoid inplace modifications.

        :param other: other excludable items to be copied
        :type other: ormar.models.excludable.ExcludableItems
        :return: copy of other
        :rtype: ormar.models.excludable.ExcludableItems
        """
        new_excludable = cls()
        for key, value in other.items.items():
            new_excludable.items[key] = value.get_copy()
        new_excludable._flatten_paths = set(other._flatten_paths)
        new_excludable._included_relation_paths = set(other._included_relation_paths)
        return new_excludable

    def include_entry_count(self) -> int:
        """
        Returns count of include items inside.
        """
        count = 0
        for key in self.items.keys():
            count += len(self.items[key].include)
        return count

    def included_relation_paths(self) -> set[str]:
        """
        Returns the relation paths that fields included with ``fields()``
        are nested in, e.g. ``{"category__created_by"}`` for
        ``fields(["category__created_by__name"])``.

        :return: dunder relation paths of the included nested fields
        :rtype: set[str]
        """
        return {"__".join(path_parts) for path_parts in self._included_relation_paths}

    def flatten_map(self) -> Optional[FlattenMap]:
        """
        Return a :class:`FlattenMap` over the stored flatten paths, built
        lazily on first call and cached for reuse. The cache is invalidated
        whenever ``_set_slot`` adds a new flatten path. Returns ``None`` when
        no flatten paths are stored, so callers can short-circuit.

        :return: FlattenMap wrapping the nested-Ellipsis dict, or ``None``
            when no flatten paths are stored
        :rtype: Optional[FlattenMap]
        """
        if not self._flatten_paths:
            return None
        if self._flatten_map_cache is None:
            self._flatten_map_cache = FlattenMap(
                data=build_flatten_map(self._flatten_paths)
            )
        return self._flatten_map_cache

    @staticmethod
    def _make_key(model_cls: type["Model"], alias: str = "") -> str:
        """
        Build the items-dict key for ``(alias, model)``. Centralized so
        every call site shares one definition of "which Excludable is
        this".
        """
        prefix = f"{alias}_" if alias else ""
        return f"{prefix}{model_cls.get_name(lower=True)}"

    @staticmethod
    def _resolve_path(
        source_model: type["Model"],
        parts_prefix: tuple,
    ) -> tuple[str, type["Model"]]:
        """
        Resolve a dunder path prefix to its target ``(alias, model)``.

        An empty prefix returns ``("", source_model)``. Goes through
        :func:`get_relationship_alias_model_and_str`, which mutates its
        ``related_parts`` argument while resolving through models - the
        prefix tuple is copied to a list to insulate the caller.

        Examples (aliases are ``alias_for`` hashes of the path, shown here
        as ``<...>``)::

            _resolve_path(Post, ())
            # => ("", Post)

            _resolve_path(Post, ("category",))
            # => ("<alias_for('category')>", Category)

            _resolve_path(Role, ("users", "categories"))
            # => ("<alias_for('users__categories')>", Category)

        :param source_model: model from which the path is rooted
        :type source_model: type[Model]
        :param parts_prefix: pre-split path segments
        :type parts_prefix: tuple
        :return: alias and target model at the prefix
        :rtype: tuple[str, type[Model]]
        """
        if not parts_prefix:
            return "", source_model
        alias, model, _, _ = get_relationship_alias_model_and_str(
            source_model=source_model,
            related_parts=list(parts_prefix),
        )
        return alias, model

    def _referenced_at(
        self,
        source_model: type["Model"],
        parts_prefix: tuple,
    ) -> bool:
        """
        Return whether this :class:`ExcludableItems` already carries any
        include or exclude entry for the model at ``parts_prefix``.

        Used by :meth:`with_projection_exclusions` to detect whether the
        user's ``fields()`` call referenced a given path - an empty
        ``Excludable`` (or none at all) means "not referenced".

        Examples, contrasting the same path under two different
        ``fields()`` specs::

            # Built from Post.objects.fields(["name"])
            #   items = {"post": Excludable(include={"name"})}

            excludable._referenced_at(Post, ())
            # => True   (Post has a non-empty include)

            excludable._referenced_at(Post, ("category",))
            # => False  (no entry for Category)


            # Built from Post.objects.fields(["name", "category__name"])
            #   items = {
            #       "post": Excludable(include={"name"}),
            #       "<alias>_category": Excludable(include={"name"}),
            #   }

            excludable._referenced_at(Post, ("category",))
            # => True   (Category has a non-empty include)

        :param source_model: model from which the path is rooted
        :type source_model: type[Model]
        :param parts_prefix: pre-split path segments to check
        :type parts_prefix: tuple
        :return: True if a non-empty entry exists at the prefix
        :rtype: bool
        """
        alias, model = self._resolve_path(source_model, parts_prefix)
        exc = self.items.get(self._make_key(model, alias))
        return exc is not None and bool(exc.include or exc.exclude)

    def get(self, model_cls: type["Model"], alias: str = "") -> Excludable:
        """
        Return Excludable for given model and alias.

        :param model_cls: target model to check
        :type model_cls: ormar.models.metaclass.ModelMetaclass
        :param alias: table alias from relation manager
        :type alias: str
        :return: Excludable for given model and alias
        :rtype: ormar.models.excludable.Excludable
        """
        key = self._make_key(model_cls, alias)
        excludable = self.items.get(key)
        if not excludable:
            excludable = Excludable()
            self.items[key] = excludable
        return excludable

    def with_entry_alias(
        self, model_cls: type["Model"], source_alias: str, target_alias: str
    ) -> "ExcludableItems":
        """
        Returns a copy in which the entry of a model stored under one alias is also
        stored under another one. Used when a model is queried from a different root
        than the one the include/exclude paths were defined from (prefetch queries).

        :param model_cls: model which entry should be re-aliased
        :type model_cls: type[Model]
        :param source_alias: alias the entry is stored under
        :type source_alias: str
        :param target_alias: alias the entry should be available under
        :type target_alias: str
        :return: copy of excludable items with the re-aliased entry
        :rtype: ExcludableItems
        """
        new_excludable = ExcludableItems.from_excludable(self)
        source = self.items.get(self._make_key(model_cls, source_alias))
        new_excludable.items[self._make_key(model_cls, target_alias)] = (
            source.get_copy() if source else Excludable()
        )
        return new_excludable

    def build(
        self,
        items: Union[list[str], str, tuple[str], set[str], dict],
        model_cls: type["Model"],
        slot: Slot = "include",
    ) -> None:
        """
        Receives the one of the types of items and parses them as to achieve
        a end situation with one excludable per alias/model in relation.

        Each excludable has three sets of values - include, exclude, and flatten.

        :param items: values to be included, excluded or flattened
        :type items: Union[list[str], str, tuple[str], set[str], dict]
        :param model_cls: source model from which relations are constructed
        :type model_cls: ormar.models.metaclass.ModelMetaclass
        :param slot: which slot to write parsed values into
        :type slot: Slot
        """
        if isinstance(items, str):
            items = {items}

        if isinstance(items, dict):
            self._traverse_dict(
                values=items,
                source_model=model_cls,
                model_cls=model_cls,
                slot=slot,
            )
        else:
            items = set(items)
            nested_items = set(x for x in items if "__" in x)
            items.difference_update(nested_items)
            if items:
                self._set_slot(
                    items=items,
                    model_cls=model_cls,
                    slot=slot,
                )
            if nested_items:
                self._traverse_list(values=nested_items, model_cls=model_cls, slot=slot)

        if slot == "flatten":
            self._validate_flatten_prefix_collisions()

    def _set_slot(
        self,
        items: set,
        model_cls: type["Model"],
        slot: Slot,
        alias: str = "",
        path_parts: PathParts = (),
    ) -> None:
        """
        Sets set of values to be stored for the given slot on the key that
        corresponds to the passed model + alias.

        :param items: items to write
        :type items: set
        :param model_cls: target model on which the items are stored
        :type model_cls: type[Model]
        :param slot: which slot to write to
        :type slot: Slot
        :param alias: table alias from relation manager
        :type alias: str
        :param path_parts: tuple of dunder path segments leading to this model
        :type path_parts: PathParts
        """
        if slot == "flatten":
            self._validate_flatten_leaves(
                items=items, model_cls=model_cls, path_parts=path_parts
            )
            for item in items:
                self._flatten_paths.add(path_parts + (item,))
            self._flatten_map_cache = None
        elif slot == "include" and path_parts:
            self._included_relation_paths.add(path_parts)

        key = self._make_key(model_cls, alias)
        excludable = self.items.setdefault(key, Excludable())
        excludable.set_values(value=items, slot=slot)

    def _traverse_dict(  # noqa: CFQ002
        self,
        values: dict,
        source_model: type["Model"],
        model_cls: type["Model"],
        slot: Slot,
        path_parts: PathParts = (),
        alias: str = "",
    ) -> None:
        """
        Goes through dict of nested values and construct/update Excludables.

        :param values: items to include/exclude/flatten
        :type values: dict
        :param source_model: source model from which relations are constructed
        :type source_model: ormar.models.metaclass.ModelMetaclass
        :param model_cls: model reached via ``path_parts``
        :type model_cls: ormar.models.metaclass.ModelMetaclass
        :param slot: which slot to write into
        :type slot: Slot
        :param path_parts: tuple of dunder path segments leading to ``model_cls``
        :type path_parts: PathParts
        :param alias: alias of relation
        :type alias: str
        """
        self_fields = set()
        for key, value in values.items():
            if value is ...:
                self_fields.add(key)
            elif isinstance(value, set):
                nested_parts = path_parts + (key,)
                table_prefix, target_model, _, _ = get_relationship_alias_model_and_str(
                    source_model=source_model,
                    related_parts=list(nested_parts),
                )
                self._set_slot(
                    items=value,
                    model_cls=target_model,
                    slot=slot,
                    alias=table_prefix,
                    path_parts=nested_parts,
                )
            else:
                nested_parts = path_parts + (key,)
                table_prefix, target_model, _, _ = get_relationship_alias_model_and_str(
                    source_model=source_model,
                    related_parts=list(nested_parts),
                )
                self._traverse_dict(
                    values=value,
                    source_model=source_model,
                    model_cls=target_model,
                    slot=slot,
                    path_parts=nested_parts,
                    alias=table_prefix,
                )
        if self_fields:
            self._set_slot(
                items=self_fields,
                model_cls=model_cls,
                slot=slot,
                alias=alias,
                path_parts=path_parts,
            )

    def _traverse_list(
        self, values: set[str], model_cls: type["Model"], slot: Slot
    ) -> None:
        """
        Consume a set of dunder-style paths (``"a__b__c"``) and write each leaf
        to the Excludable for its target model/alias. Each path is split once
        into a tuple and threaded through ``_set_slot`` — no further string
        joins happen downstream.

        :param values: set of dunder-style path strings
        :type values: set[str]
        :param model_cls: source model from which relations are resolved
        :type model_cls: type[Model]
        :param slot: which slot to write into
        :type slot: Slot
        """
        for dunder_path in values:
            parts = tuple(dunder_path.split("__"))
            table_prefix, target_model, _, _ = get_relationship_alias_model_and_str(
                source_model=model_cls,
                related_parts=list(parts[:-1]),
            )
            self._set_slot(
                items={parts[-1]},
                model_cls=target_model,
                slot=slot,
                alias=table_prefix,
                path_parts=parts[:-1],
            )

    @staticmethod
    def _validate_flatten_leaves(
        items: set, model_cls: type["Model"], path_parts: PathParts
    ) -> None:
        """
        Ensure every leaf addressed by a flatten spec is a real relation on the
        target model (not a scalar column and not a through model).

        :param items: set of leaf names being flattened on ``model_cls``
        :type items: set
        :param model_cls: target model on which leaves must resolve to relations
        :type model_cls: type[Model]
        :param path_parts: tuple of segments leading to ``model_cls`` (only
            joined for error messages, never parsed)
        :type path_parts: PathParts
        """
        model_fields = model_cls.ormar_config.model_fields
        for item in items:
            related_field = model_fields.get(item)
            if related_field is None:
                raise QueryDefinitionError(
                    f"Unknown relation '{item}' on model "
                    f"{model_cls.get_name(lower=False)} in flatten_fields path "
                    f"'{join_path(path_parts, item)}'."
                )
            if getattr(related_field, "is_through", False):
                raise QueryDefinitionError(
                    f"Cannot flatten through model '{item}' at path "
                    f"'{join_path(path_parts, item)}'. Flatten the many-to-many "
                    f"relation itself instead."
                )
            if not getattr(related_field, "is_relation", False):
                raise QueryDefinitionError(
                    f"flatten_fields target '{join_path(path_parts, item)}' is "
                    f"not a relation on model {model_cls.get_name(lower=False)}. "
                    f"Only foreign keys, many-to-many, and reverse relations can "
                    f"be flattened."
                )

    def _validate_flatten_prefix_collisions(self) -> None:
        """
        Ensure no flatten path is a strict ancestor of another. Flattening a
        relation replaces it with a scalar PK, so a deeper flatten through the
        same chain is unreachable.

        Works directly on tuple paths — sorted so each prefix's descendants
        follow it immediately, enabling an early break once the prefix no
        longer matches.

        :raises QueryDefinitionError: on any prefix collision
        """
        paths = sorted(self._flatten_paths)
        for i, short in enumerate(paths):
            short_len = len(short)
            for longer in paths[i + 1 :]:
                if longer[:short_len] != short:
                    break
                raise QueryDefinitionError(
                    f"Conflicting flatten directives: "
                    f"'{join_path(short)}' is flattened to its primary key, "
                    f"so nested flatten '{join_path(longer)}' is unreachable."
                )

    def with_projection_exclusions(
        self,
        source_model: type["Model"],
        select_related: list[str],
    ) -> "ExcludableItems":
        """
        Return a copy with relations not referenced by ``fields()`` removed
        from a flat values projection.

        A filter like ``filter(project__id=...)`` auto-joins ``project``;
        without this, a flat ``values()`` call leaks every Project column
        even though only one main-model field was requested. Returns the
        original instance unchanged when ``fields()`` was never called -
        the leak is a values-projection problem, not an ORM-load problem.

        :param source_model: model from which relation paths are rooted
        :type source_model: type[Model]
        :param select_related: paths joined into the query (dunder strings)
        :type select_related: list[str]
        :return: new :class:`ExcludableItems` with implicit excludes added,
            or ``self`` when no ``fields()`` call had any effect
        :rtype: ExcludableItems
        """
        if self.include_entry_count() == 0:
            return self

        excludable = ExcludableItems.from_excludable(self)

        # If fields() never names the source model, project only its PK.
        if not excludable._referenced_at(source_model, ()):
            excludable.get(source_model).pk_only = True

        for path in select_related:
            parts = tuple(path.split("__"))
            # Snapshot which prefixes carry a fields() reference before any
            # exclusions are added below - the exclude additions would
            # otherwise show up as "referenced" on the next iteration.
            referenced = [
                excludable._referenced_at(source_model, parts[: d + 1])
                for d in range(len(parts))
            ]
            # Walk deepest-first so kept_deeper accumulates inward. Each
            # segment still needs its own exclude when not kept, because
            # values_column_map only consults the immediate parent.
            kept_deeper = False
            for i in reversed(range(len(parts))):
                kept_deeper = kept_deeper or referenced[i]
                segment = parts[i]
                parent_alias, parent_model = excludable._resolve_path(
                    source_model, parts[:i]
                )
                parent_exc = excludable.get(parent_model, alias=parent_alias)
                if parent_exc.is_explicitly_included(segment):
                    continue
                if kept_deeper:
                    # Intermediate relation: keep the join but project
                    # PK-only when this segment was never explicitly named.
                    if not referenced[i]:
                        target_alias, target_model = excludable._resolve_path(
                            source_model, parts[: i + 1]
                        )
                        excludable.get(target_model, alias=target_alias).pk_only = True
                    continue
                field = parent_model.ormar_config.model_fields[segment]
                parent_exc.exclude.add(segment)
                if field.is_multi:
                    parent_exc.exclude.add(field.through.get_name())

        return excludable

    def validate_flatten_vs_excludable(self, source_model: type["Model"]) -> None:
        """
        Ensure no flattened relation has sub-field include/exclude on its target.
        Whole-relation include/exclude at the parent level is allowed; only
        sub-field selection on the flattened child is flagged.

        :param source_model: model from which flatten paths are rooted
        :type source_model: type[Model]
        :raises QueryDefinitionError: when a flattened relation has sub-field
            include/exclude on its target model
        """
        for parts in self._flatten_paths:
            table_prefix, target_model, _, _ = get_relationship_alias_model_and_str(
                source_model=source_model,
                related_parts=list(parts),
            )
            child = self.items.get(self._make_key(target_model, table_prefix))
            if not child:
                continue
            conflicts = (child.include | child.exclude) - {...}
            if conflicts:
                raise QueryDefinitionError(
                    f"Flatten conflict: relation '{join_path(parts)}' is "
                    f"flattened but include/exclude specifies children "
                    f"{sorted(conflicts)}. A flattened relation renders only "
                    f"its primary key and cannot have children selected."
                )

build(items, model_cls, slot='include')

Receives the one of the types of items and parses them as to achieve a end situation with one excludable per alias/model in relation.

Each excludable has three sets of values - include, exclude, and flatten.

Parameters:

Name Type Description Default
items Union[list[str], str, tuple[str], set[str], dict]

values to be included, excluded or flattened

required
model_cls type[Model]

source model from which relations are constructed

required
slot Slot

which slot to write parsed values into

'include'
Source code in ormar/models/excludable.py
Python
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
def build(
    self,
    items: Union[list[str], str, tuple[str], set[str], dict],
    model_cls: type["Model"],
    slot: Slot = "include",
) -> None:
    """
    Receives the one of the types of items and parses them as to achieve
    a end situation with one excludable per alias/model in relation.

    Each excludable has three sets of values - include, exclude, and flatten.

    :param items: values to be included, excluded or flattened
    :type items: Union[list[str], str, tuple[str], set[str], dict]
    :param model_cls: source model from which relations are constructed
    :type model_cls: ormar.models.metaclass.ModelMetaclass
    :param slot: which slot to write parsed values into
    :type slot: Slot
    """
    if isinstance(items, str):
        items = {items}

    if isinstance(items, dict):
        self._traverse_dict(
            values=items,
            source_model=model_cls,
            model_cls=model_cls,
            slot=slot,
        )
    else:
        items = set(items)
        nested_items = set(x for x in items if "__" in x)
        items.difference_update(nested_items)
        if items:
            self._set_slot(
                items=items,
                model_cls=model_cls,
                slot=slot,
            )
        if nested_items:
            self._traverse_list(values=nested_items, model_cls=model_cls, slot=slot)

    if slot == "flatten":
        self._validate_flatten_prefix_collisions()

flatten_map()

Return a :class:FlattenMap over the stored flatten paths, built lazily on first call and cached for reuse. The cache is invalidated whenever _set_slot adds a new flatten path. Returns None when no flatten paths are stored, so callers can short-circuit.

Returns:

Type Description
Optional[FlattenMap]

FlattenMap wrapping the nested-Ellipsis dict, or None when no flatten paths are stored

Source code in ormar/models/excludable.py
Python
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
def flatten_map(self) -> Optional[FlattenMap]:
    """
    Return a :class:`FlattenMap` over the stored flatten paths, built
    lazily on first call and cached for reuse. The cache is invalidated
    whenever ``_set_slot`` adds a new flatten path. Returns ``None`` when
    no flatten paths are stored, so callers can short-circuit.

    :return: FlattenMap wrapping the nested-Ellipsis dict, or ``None``
        when no flatten paths are stored
    :rtype: Optional[FlattenMap]
    """
    if not self._flatten_paths:
        return None
    if self._flatten_map_cache is None:
        self._flatten_map_cache = FlattenMap(
            data=build_flatten_map(self._flatten_paths)
        )
    return self._flatten_map_cache

from_excludable(other) classmethod

Copy passed ExcludableItems to avoid inplace modifications.

Parameters:

Name Type Description Default
other ExcludableItems

other excludable items to be copied

required

Returns:

Type Description
ormar.models.excludable.ExcludableItems

copy of other

Source code in ormar/models/excludable.py
Python
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
@classmethod
def from_excludable(cls, other: "ExcludableItems") -> "ExcludableItems":
    """
    Copy passed ExcludableItems to avoid inplace modifications.

    :param other: other excludable items to be copied
    :type other: ormar.models.excludable.ExcludableItems
    :return: copy of other
    :rtype: ormar.models.excludable.ExcludableItems
    """
    new_excludable = cls()
    for key, value in other.items.items():
        new_excludable.items[key] = value.get_copy()
    new_excludable._flatten_paths = set(other._flatten_paths)
    new_excludable._included_relation_paths = set(other._included_relation_paths)
    return new_excludable

get(model_cls, alias='')

Return Excludable for given model and alias.

Parameters:

Name Type Description Default
model_cls type[Model]

target model to check

required
alias str

table alias from relation manager

''

Returns:

Type Description
ormar.models.excludable.Excludable

Excludable for given model and alias

Source code in ormar/models/excludable.py
Python
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
def get(self, model_cls: type["Model"], alias: str = "") -> Excludable:
    """
    Return Excludable for given model and alias.

    :param model_cls: target model to check
    :type model_cls: ormar.models.metaclass.ModelMetaclass
    :param alias: table alias from relation manager
    :type alias: str
    :return: Excludable for given model and alias
    :rtype: ormar.models.excludable.Excludable
    """
    key = self._make_key(model_cls, alias)
    excludable = self.items.get(key)
    if not excludable:
        excludable = Excludable()
        self.items[key] = excludable
    return excludable

include_entry_count()

Returns count of include items inside.

Source code in ormar/models/excludable.py
Python
375
376
377
378
379
380
381
382
def include_entry_count(self) -> int:
    """
    Returns count of include items inside.
    """
    count = 0
    for key in self.items.keys():
        count += len(self.items[key].include)
    return count

included_relation_paths()

Returns the relation paths that fields included with fields() are nested in, e.g. {"category__created_by"} for fields(["category__created_by__name"]).

Returns:

Type Description
set[str]

dunder relation paths of the included nested fields

Source code in ormar/models/excludable.py
Python
384
385
386
387
388
389
390
391
392
393
def included_relation_paths(self) -> set[str]:
    """
    Returns the relation paths that fields included with ``fields()``
    are nested in, e.g. ``{"category__created_by"}`` for
    ``fields(["category__created_by__name"])``.

    :return: dunder relation paths of the included nested fields
    :rtype: set[str]
    """
    return {"__".join(path_parts) for path_parts in self._included_relation_paths}

validate_flatten_vs_excludable(source_model)

Ensure no flattened relation has sub-field include/exclude on its target. Whole-relation include/exclude at the parent level is allowed; only sub-field selection on the flattened child is flagged.

Parameters:

Name Type Description Default
source_model type[Model]

model from which flatten paths are rooted

required

Raises:

Type Description
QueryDefinitionError

when a flattened relation has sub-field include/exclude on its target model

Source code in ormar/models/excludable.py
Python
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
def validate_flatten_vs_excludable(self, source_model: type["Model"]) -> None:
    """
    Ensure no flattened relation has sub-field include/exclude on its target.
    Whole-relation include/exclude at the parent level is allowed; only
    sub-field selection on the flattened child is flagged.

    :param source_model: model from which flatten paths are rooted
    :type source_model: type[Model]
    :raises QueryDefinitionError: when a flattened relation has sub-field
        include/exclude on its target model
    """
    for parts in self._flatten_paths:
        table_prefix, target_model, _, _ = get_relationship_alias_model_and_str(
            source_model=source_model,
            related_parts=list(parts),
        )
        child = self.items.get(self._make_key(target_model, table_prefix))
        if not child:
            continue
        conflicts = (child.include | child.exclude) - {...}
        if conflicts:
            raise QueryDefinitionError(
                f"Flatten conflict: relation '{join_path(parts)}' is "
                f"flattened but include/exclude specifies children "
                f"{sorted(conflicts)}. A flattened relation renders only "
                f"its primary key and cannot have children selected."
            )

with_entry_alias(model_cls, source_alias, target_alias)

Returns a copy in which the entry of a model stored under one alias is also stored under another one. Used when a model is queried from a different root than the one the include/exclude paths were defined from (prefetch queries).

Parameters:

Name Type Description Default
model_cls type[Model]

model which entry should be re-aliased

required
source_alias str

alias the entry is stored under

required
target_alias str

alias the entry should be available under

required

Returns:

Type Description
ExcludableItems

copy of excludable items with the re-aliased entry

Source code in ormar/models/excludable.py
Python
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
def with_entry_alias(
    self, model_cls: type["Model"], source_alias: str, target_alias: str
) -> "ExcludableItems":
    """
    Returns a copy in which the entry of a model stored under one alias is also
    stored under another one. Used when a model is queried from a different root
    than the one the include/exclude paths were defined from (prefetch queries).

    :param model_cls: model which entry should be re-aliased
    :type model_cls: type[Model]
    :param source_alias: alias the entry is stored under
    :type source_alias: str
    :param target_alias: alias the entry should be available under
    :type target_alias: str
    :return: copy of excludable items with the re-aliased entry
    :rtype: ExcludableItems
    """
    new_excludable = ExcludableItems.from_excludable(self)
    source = self.items.get(self._make_key(model_cls, source_alias))
    new_excludable.items[self._make_key(model_cls, target_alias)] = (
        source.get_copy() if source else Excludable()
    )
    return new_excludable

with_projection_exclusions(source_model, select_related)

Return a copy with relations not referenced by fields() removed from a flat values projection.

A filter like filter(project__id=...) auto-joins project; without this, a flat values() call leaks every Project column even though only one main-model field was requested. Returns the original instance unchanged when fields() was never called - the leak is a values-projection problem, not an ORM-load problem.

Parameters:

Name Type Description Default
source_model type[Model]

model from which relation paths are rooted

required
select_related list[str]

paths joined into the query (dunder strings)

required

Returns:

Type Description
ExcludableItems

new :class:ExcludableItems with implicit excludes added, or self when no fields() call had any effect

Source code in ormar/models/excludable.py
Python
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
def with_projection_exclusions(
    self,
    source_model: type["Model"],
    select_related: list[str],
) -> "ExcludableItems":
    """
    Return a copy with relations not referenced by ``fields()`` removed
    from a flat values projection.

    A filter like ``filter(project__id=...)`` auto-joins ``project``;
    without this, a flat ``values()`` call leaks every Project column
    even though only one main-model field was requested. Returns the
    original instance unchanged when ``fields()`` was never called -
    the leak is a values-projection problem, not an ORM-load problem.

    :param source_model: model from which relation paths are rooted
    :type source_model: type[Model]
    :param select_related: paths joined into the query (dunder strings)
    :type select_related: list[str]
    :return: new :class:`ExcludableItems` with implicit excludes added,
        or ``self`` when no ``fields()`` call had any effect
    :rtype: ExcludableItems
    """
    if self.include_entry_count() == 0:
        return self

    excludable = ExcludableItems.from_excludable(self)

    # If fields() never names the source model, project only its PK.
    if not excludable._referenced_at(source_model, ()):
        excludable.get(source_model).pk_only = True

    for path in select_related:
        parts = tuple(path.split("__"))
        # Snapshot which prefixes carry a fields() reference before any
        # exclusions are added below - the exclude additions would
        # otherwise show up as "referenced" on the next iteration.
        referenced = [
            excludable._referenced_at(source_model, parts[: d + 1])
            for d in range(len(parts))
        ]
        # Walk deepest-first so kept_deeper accumulates inward. Each
        # segment still needs its own exclude when not kept, because
        # values_column_map only consults the immediate parent.
        kept_deeper = False
        for i in reversed(range(len(parts))):
            kept_deeper = kept_deeper or referenced[i]
            segment = parts[i]
            parent_alias, parent_model = excludable._resolve_path(
                source_model, parts[:i]
            )
            parent_exc = excludable.get(parent_model, alias=parent_alias)
            if parent_exc.is_explicitly_included(segment):
                continue
            if kept_deeper:
                # Intermediate relation: keep the join but project
                # PK-only when this segment was never explicitly named.
                if not referenced[i]:
                    target_alias, target_model = excludable._resolve_path(
                        source_model, parts[: i + 1]
                    )
                    excludable.get(target_model, alias=target_alias).pk_only = True
                continue
            field = parent_model.ormar_config.model_fields[segment]
            parent_exc.exclude.add(segment)
            if field.is_multi:
                parent_exc.exclude.add(field.through.get_name())

    return excludable

F

Bases: Expression

Field by its path from the queried model: F("capacity"), or in filters also a field of a related model (filter(taken__lt=F("owner__limit"))).

Source code in ormar/queryset/expressions.py
Python
86
87
88
89
90
91
92
93
94
95
96
97
class F(Expression):
    """
    Field by its path from the queried model: ``F("capacity")``, or in filters
    also a field of a related model (``filter(taken__lt=F("owner__limit"))``).
    """

    def __init__(self, path: str) -> None:
        """
        :param path: field name, prefixed by its relation path if any
        :type path: str
        """
        self._path = path

__init__(path)

Parameters:

Name Type Description Default
path str

field name, prefixed by its relation path if any

required
Source code in ormar/queryset/expressions.py
Python
92
93
94
95
96
97
def __init__(self, path: str) -> None:
    """
    :param path: field name, prefixed by its relation path if any
    :type path: str
    """
    self._path = path

Float

Bases: ModelFieldFactory, float

Float field factory that construct Field classes and populated their values.

Source code in ormar/fields/model_fields.py
Python
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
class Float(ModelFieldFactory, float):
    """
    Float field factory that construct Field classes and populated their values.
    """

    _type = float
    _sample = 0.0

    def __new__(  # type: ignore
        cls,
        *,
        minimum: Optional[float] = None,
        maximum: Optional[float] = None,
        multiple_of: Optional[int] = None,
        **kwargs: Any,
    ) -> Self:
        kwargs = {
            **kwargs,
            **{
                k: v
                for k, v in locals().items()
                if k not in ["cls", "__class__", "kwargs"]
            },
        }
        kwargs["ge"] = kwargs["minimum"]
        kwargs["le"] = kwargs["maximum"]
        return super().__new__(cls, **kwargs)

    @classmethod
    def get_column_type(cls, **kwargs: Any) -> Any:
        """
        Return proper type of db column for given field type.
        Accepts required and optional parameters that each column type accepts.

        :param kwargs: key, value pairs of sqlalchemy options
        :type kwargs: Any
        :return: initialized column with proper options
        :rtype: sqlalchemy Column
        """
        return sqlalchemy.Float()

get_column_type(**kwargs) classmethod

Return proper type of db column for given field type. Accepts required and optional parameters that each column type accepts.

Parameters:

Name Type Description Default
kwargs Any

key, value pairs of sqlalchemy options

{}

Returns:

Type Description
sqlalchemy Column

initialized column with proper options

Source code in ormar/fields/model_fields.py
Python
393
394
395
396
397
398
399
400
401
402
403
404
@classmethod
def get_column_type(cls, **kwargs: Any) -> Any:
    """
    Return proper type of db column for given field type.
    Accepts required and optional parameters that each column type accepts.

    :param kwargs: key, value pairs of sqlalchemy options
    :type kwargs: Any
    :return: initialized column with proper options
    :rtype: sqlalchemy Column
    """
    return sqlalchemy.Float()

ForeignKeyField

Bases: BaseField

Actual class returned from ForeignKey function call and stored in model_fields.

Source code in ormar/fields/foreign_key.py
Python
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
class ForeignKeyField(BaseField):  # type: ignore[misc]
    """
    Actual class returned from ForeignKey function call and stored in model_fields.
    """

    def __init__(self, **kwargs: Any) -> None:
        if TYPE_CHECKING:  # pragma: no cover
            self.__type__: type
            self.to: type["Model"]
        self.ondelete: str = kwargs.pop("ondelete", None)
        self.onupdate: str = kwargs.pop("onupdate", None)
        self.foreign_key_name: Optional[str] = kwargs.pop("foreign_key_name", None)
        self.to_field: Union[str, list[str], tuple[str, ...], None] = kwargs.pop(
            "to_field", None
        )
        self.columns: Optional[dict[str, str]] = kwargs.pop("columns", None)
        self.db_constraint: bool = kwargs.pop("db_constraint", True)
        self.deferred_related_name_checks: list[ForeignKeyField] = []
        super().__init__(**kwargs)

    def construct_constraints(self) -> list:
        """
        Build the SQLAlchemy foreign keys of the field's column from its link,
        one per column pair, named ``foreign_key_name`` or
        ``fk_<owner table>_<target table>_<target column>_<field name>``.
        Built on every call, as SQLAlchemy binds a ForeignKey to one table and
        subclasses need their own.

        :return: SQLAlchemy foreign keys, empty until the target is resolved
        :rtype: list
        """
        if (
            self.virtual
            or not self.db_constraint
            or self.has_unresolved_forward_refs()
            or self.owner.ormar_config.view
        ):
            return []
        owner_table = self.owner.ormar_config.tablename
        target_table = self.to.ormar_config.tablename
        return [
            sqlalchemy.ForeignKey(
                column=qualified_fk_reference(
                    target=self.to, column_alias=pair.target_column
                ),
                ondelete=self.ondelete,
                onupdate=self.onupdate,
                name=self.foreign_key_name
                or f"fk_{owner_table}_{target_table}_{pair.target_column}_{self.name}",
            )
            for pair in self.link.pairs
        ]

    @property
    def kind(self) -> RelationKind:
        """
        :return: forward or reverse side of a foreign key or one-to-one relation
        :rtype: RelationKind
        """
        return FOREIGN_KEY_KINDS[(self.one_to_one, self.virtual)]

    def get_related_name(self) -> str:
        """
        Returns name to use for reverse relation.
        It's either set as `related_name` or by default it's owner model. get_name + 's'
        :return: name of the related_name or default related name.
        :rtype: str
        """
        suffix = "" if self.one_to_one else "s"
        return self.related_name or self.owner.get_name() + suffix

    def default_target_field_name(self) -> str:
        """
        Returns default target model name on through model.
        :return: name of the field
        :rtype: str
        """
        prefix = "from_" if self.self_reference else ""
        return self.through_reverse_relation_name or f"{prefix}{self.to.get_name()}"

    def default_source_field_name(self) -> str:
        """
        Returns default target model name on through model.
        :return: name of the field
        :rtype: str
        """
        prefix = "to_" if self.self_reference else ""
        return self.through_relation_name or f"{prefix}{self.owner.get_name()}"

    def get_filter_clause_target(self) -> type["Model"]:
        return self.to

    @property
    def link(self) -> RelationLink:
        """
        Columns connecting the owner's table to the table of the related model,
        built once per owner and target: a field copied to another model
        (inheritance) or re-targeted (forward refs) builds its own link.

        :return: link from the owner to the related model
        :rtype: RelationLink
        """
        cache_key = (self.owner, self.to, self.through)
        cached = self.__dict__.get("link_cache")
        if cached is not None and cached[0] == cache_key:
            return cached[1]
        link = self.build_link()
        self.__dict__["link_cache"] = (cache_key, link)
        return link

    def build_link(self) -> RelationLink:
        """
        A foreign key links its own column to the target's primary key, a
        reverse relation is the mirror of the foreign key it was created from.

        :return: link from the owner to the related model
        :rtype: RelationLink
        """
        if self.virtual:
            forward = self.to.ormar_config.model_fields[self.get_related_name()]
            return cast("ForeignKeyField", forward).link.mirrored()
        columns = referenced_columns(to=self.to, to_field=self.to_field)
        return RelationLink(
            source=self.owner,
            target=self.to,
            pairs=tuple(
                ColumnPair(
                    source_field=self.name,
                    source_column=self.local_column(
                        target_column=column, several=len(columns) > 1
                    ),
                    target_field=field,
                    target_column=column,
                )
                for column, field in columns.items()
            ),
        )

    def target_fields(self) -> tuple[str, ...]:
        """
        :return: fields of the related model the foreign key references: its
            ``to_field`` or its primary key fields
        :rtype: tuple[str, ...]
        """
        names = to_field_names(to_field=self.to_field)
        if names is not None:
            return names
        return self.to.ormar_config.pk.fields

    def local_column(self, target_column: str, several: bool) -> str:
        """
        :param target_column: referenced column of the related model's table
        :type target_column: str
        :param several: whether the foreign key references several columns
        :type several: bool
        :return: name of the owner's column storing it: from ``columns=``, the
            field's own column for a single-column key, or
            ``<field>_<referenced column>`` for keys of several columns
        :rtype: str
        """
        if self.columns is not None:
            return self.columns[target_column]
        if not several:
            return self.get_alias()
        return f"{self.name}_{target_column}"

    def get_columns(self) -> list[sqlalchemy.Column]:
        """
        :return: the owner's columns of the foreign key, one per referenced
            column (a placeholder single column until a forward reference is
            resolved)
        :rtype: list[sqlalchemy.Column]
        """
        if self.has_unresolved_forward_refs():
            return [self.get_column(self.get_alias())]
        pairs = self.link.pairs
        if len(pairs) == 1:
            return [self.get_column(pairs[0].source_column)]
        return [
            sqlalchemy.Column(
                name=pair.source_column,
                type_=column_type(
                    model=self.to, field=pair.target_field, column=pair.target_column
                ),
                nullable=self.sql_nullable,
                primary_key=self.primary_key,
                autoincrement=False,
            )
            for pair in pairs
        ]

    def column_aliases(self) -> tuple[str, ...]:
        """
        :return: the owner's column names of the foreign key
        :rtype: tuple[str, ...]
        """
        if self.virtual or self.has_unresolved_forward_refs():
            return (self.get_alias(),)
        return self.link.source_columns()

    def construct_table_constraints(self) -> list:
        """
        :return: the table-level items of a foreign key of several columns:
            its ``FOREIGN KEY (a, b) REFERENCES t (x, y)``, and a composite
            unique constraint / index when the field is unique / indexed;
            empty for other fields
        :rtype: list
        """
        if (
            not self.kind.holds_columns
            or self.has_unresolved_forward_refs()
            or self.owner.ormar_config.view
        ):
            return []
        pairs = self.link.pairs
        if len(pairs) == 1:
            return []
        columns = [pair.source_column for pair in pairs]
        owner_table = self.owner.ormar_config.tablename
        target_table = self.to.ormar_config.tablename
        items: list = []
        if self.db_constraint:
            items.append(
                sqlalchemy.ForeignKeyConstraint(
                    columns=columns,
                    refcolumns=[
                        qualified_fk_reference(
                            target=self.to, column_alias=pair.target_column
                        )
                        for pair in pairs
                    ],
                    ondelete=self.ondelete,
                    onupdate=self.onupdate,
                    name=self.foreign_key_name
                    or f"fk_{owner_table}_{target_table}_{self.name}",
                )
            )
        if self.unique:
            items.append(
                sqlalchemy.UniqueConstraint(
                    *columns, name=f"uc_{owner_table}_{self.name}"
                )
            )
        if self.index:
            items.append(sqlalchemy.Index(f"ix_{owner_table}_{self.name}", *columns))
        return items

    def _evaluate_forward_ref(
        self, globalns: Any, localns: Any, is_through: bool = False
    ) -> None:
        target = "through" if is_through else "to"
        target_obj = getattr(self, target)
        if sys.version_info.minor <= 8:  # pragma: no cover
            evaluated = target_obj._evaluate(globalns, localns)
        else:  # pragma: no cover
            evaluated = target_obj._evaluate(globalns, localns, recursive_guard=set())
        setattr(self, target, evaluated)

    def evaluate_forward_ref(self, globalns: Any, localns: Any) -> None:
        """
        Evaluates the ForwardRef to actual Field based on global and local namespaces

        :param globalns: global namespace
        :type globalns: Any
        :param localns: local namespace
        :type localns: Any
        :return: None
        :rtype: None
        """
        if self.to.__class__ == ForwardRef:
            self._evaluate_forward_ref(globalns, localns)
            validate_view_target(
                to=self.to, virtual=self.virtual, db_constraint=self.db_constraint
            )
            params = populate_fk_params_based_on_to_model(
                to=self.to,
                nullable=self.nullable,
                virtual=self.virtual,
                to_field=self.to_field,
            )
            if not self.virtual:
                validate_link_columns(
                    to=self.to,
                    to_field=self.to_field,
                    columns=self.columns,
                    name=self.db_alias,
                )
            self.__type__ = params.annotation
            self.column_type = params.column_type
            self.to_key_only = params.key_only_model

    def _extract_model_from_sequence(
        self, value: list, child: "Model", to_register: bool
    ) -> list["Model"]:
        """
        Takes a list of Models and registers them on parent.
        Registration is mutual, so children have also reference to parent.

        Used in reverse FK relations.

        :param value: list of Model
        :type value: list
        :param child: child/ related Model
        :type child: Model
        :param to_register: flag if the relation should be set in RelationshipManager
        :type to_register: bool
        :return: list (if needed) registered Models
        :rtype: list["Model"]
        """
        return [
            self.expand_relationship(  # type: ignore
                # a key of several columns given as a JSON list
                value=tuple(val) if val.__class__ is list else val,
                child=child,
                to_register=to_register,
            )
            for val in value
        ]

    def _construct_model_from_dict(
        self, value: dict, child: "Model", to_register: bool
    ) -> "Model":
        """
        Takes a dictionary, creates a instance and registers it for parent.
        If dictionary holds only the referenced key fields it is a __pk_only__
        model. Related fields may be present if they are None, empty or the
        relation back to the child (as in serialized responses), any other
        related value makes it a full model, so nested related models are kept.
        Registration is mutual, so children have also reference to parent.

        Used in normal FK for dictionaries.

        :param value: dictionary of a Model
        :type value: dict
        :param child: child/ related Model
        :type child: Model
        :param to_register: flag if the relation should be set in RelationshipManager
        :type to_register: bool
        :return: (if needed) registered Model
        :rtype: Model
        """
        key_only_model = None
        target_fields = self.target_fields()
        related_names = self.to.extract_related_names()
        own_keys = set(value.keys()) - related_names
        nested_keys = value.keys() & related_names - {self.get_related_name()}
        if (
            own_keys == set(target_fields)
            and all(value.get(field) is not None for field in target_fields)
            and all(value[name] is None or value[name] == [] for name in nested_keys)
            and not self.is_through
        ):
            key_only_model = self.to_key_only(**value)
            model = cast(
                "Model",
                self.to._internal_construct(_pk_only=True, _excluded=None, **value),
            )
        else:
            model = self.to(**value)
        if to_register:
            self.register_relation(model=model, child=child)
        return key_only_model if key_only_model is not None else model

    def _construct_model_from_pk(
        self, value: Any, child: "Model", to_register: bool
    ) -> "Model":
        """
        Takes a pk value, creates a dummy instance and registers it for parent.
        Registration is mutual, so children have also reference to parent.

        Used in normal FK for dictionaries.

        :param value: value of a related pk / fk column
        :type value: Any
        :param child: child/ related Model
        :type child: Model
        :param to_register: flag if the relation should be set in RelationshipManager
        :type to_register: bool
        :return: (if needed) registered Model
        :rtype: Model
        """
        model = self.construct_key_only_model(value=value)
        if to_register:
            self.register_relation(model=model, child=child)
        return model

    def construct_key_only_model(self, value: Any) -> "Model":
        """
        Takes a key value and creates an instance of the related model with
        only the key populated, without registering it on any side.

        :param value: value of a related pk / fk column
        :type value: Any
        :raises RelationshipInstanceError: if value does not match the pk type
        :return: related model with only pk set
        :rtype: Model
        """
        if isinstance(value, self.to_key_only):
            values = {field: getattr(value, field) for field in self.target_fields()}
            return key_only_instance(target=self.to, values=values)
        value_type = self.target_value_type()
        if value_type == uuid.UUID and isinstance(value, str):  # pragma: nocover
            value = uuid.UUID(value)
        if not isinstance(value, value_type):
            raise RelationshipInstanceError(
                f"Relationship error - ForeignKey {self.to.__name__} "
                f"is of type {value_type} "
                f"while {type(value)} passed as a parameter."
            )
        return key_only_instance(target=self.to, values=self.target_values(value=value))

    def target_value_of(self, related: Any) -> Any:
        """
        :param related: related model, its key-only model, a dict of its
            fields or a raw value
        :type related: Any
        :return: the value this foreign key stores for it, ``None`` when the
            related model lacks it
        :rtype: Any
        """
        return self.link.values_for(related=related)[self.name]

    def flat_fields(self) -> tuple[str, ...]:
        """
        :return: fields of a related model that represent it in flattened
            output: the referenced fields of a foreign key, the primary key
            of a reverse or many-to-many relation
        :rtype: tuple[str, ...]
        """
        if not self.kind.holds_columns:
            return self.to.ormar_config.pk.fields
        return self.target_fields()

    def flat_value(self, related: "Model") -> Any:
        """
        Represent a related model in flattened output (``flatten_fields``)::

            Track.album -> 4
            Address.country (to_field="iso_code") -> "PL"
            OrderLine.order (two columns) -> {"tenant_id": 1, "number": 7}
            Shift.membership -> {"tenant_id": 1, "member": {...}, "team": {...}}

        A referenced field that is itself a relation (a key holding a foreign
        key) is represented by its own flattened value.

        :param related: related model
        :type related: Model
        :return: the referenced value, a dict of them for several fields
        :rtype: Any
        """
        return self.flat_from_columns(
            values={
                column: column_value(model=self.to, data=related, column=column)
                for column in self.flat_columns()
            }
        )

    def flat_columns(self) -> tuple[str, ...]:
        """
        :return: columns of the related model holding ``flat_fields``
        :rtype: tuple[str, ...]
        """
        if not self.kind.holds_columns:
            return self.to.ormar_config.pk.column_aliases()
        return self.link.target_columns()

    def flat_from_columns(self, values: dict[str, Any]) -> Any:
        """
        Build the flattened representation of a related model (see
        ``flat_value``) out of the values of its ``flat_columns``.

        :param values: values of the related model's columns by column name
        :type values: dict[str, Any]
        :return: the referenced value, a dict of them for several fields
        :rtype: Any
        """
        fields = self.flat_fields()
        flat = {
            field: flat_field_from_columns(model=self.to, field=field, values=values)
            for field in fields
        }
        return flat[fields[0]] if len(fields) == 1 else flat

    def flat_value_type(self) -> Any:
        """
        :return: python type of a flattened related model (see ``flat_value``)
        :rtype: Any
        """
        fields = self.flat_fields()
        if len(fields) > 1:
            return key_dict_type(target=self.to, fields=fields)
        return flat_field_type(model=self.to, field=fields[0])

    def target_value_type(self) -> Any:
        """
        :return: python type of a raw value of the relation: the ``to_field``
            type or the related model's key type
        :rtype: Any
        """
        names = to_field_names(to_field=self.to_field)
        if names is None:
            return self.to.ormar_config.pk.python_type()
        if len(names) == 1:
            return self.to.ormar_config.model_fields[names[0]].__type__
        return tuple

    def target_values(self, value: Any) -> dict[str, Any]:
        """
        :param value: raw value of the relation
        :type value: Any
        :return: the value split into the referenced fields of the related model
        :rtype: dict[str, Any]
        """
        names = to_field_names(to_field=self.to_field)
        if names is None:
            return self.to.ormar_config.pk.to_dict(value=value)
        return dict(zip(names, key_parts(value=value, size=len(names))))

    def register_relation(self, model: "Model", child: "Model") -> None:
        """
        Registers relation between parent and child in relation manager.
        Relation manager is kep on each model (different instance).

        Used in Metaclass and sometimes some relations are missing
        (i.e. cloned Models in fastapi might miss one).

        :param model: parent model (with relation definition)
        :type model: Model class
        :param child: child model
        :type child: Model class
        """
        model._orm.add(parent=model, child=child, field=self)

    def has_unresolved_forward_refs(self) -> bool:
        """
        Verifies if the filed has any ForwardRefs that require updating before the
        model can be used.

        :return: result of the check
        :rtype: bool
        """
        return self.to.__class__ == ForwardRef

    @cached_property
    def _constructor_dispatch(self) -> dict[str, Any]:
        """
        Per-field map from input class name to the constructor handling that
        shape. Built once at first access — by the time
        ``expand_relationship`` runs, ``_verify_model_can_be_initialized``
        has already gated on ``requires_ref_update``, so the bound methods
        captured here are stable.

        :return: dispatch table for the slow path of ``expand_relationship``
        :rtype: dict[str, Any]
        """
        return {
            "dict": self._construct_model_from_dict,
            "list": self._extract_model_from_sequence,
        }

    def expand_relationship(
        self,
        value: Any,
        child: Union["Model", "NewBaseModel"],
        to_register: bool = True,
    ) -> Optional[Union["Model", list["Model"]]]:
        """
        For relations the child model is first constructed (if needed),
        registered in relation and returned.
        For relation fields the value can be a pk value (Any type of field),
        dict (from Model) or actual instance/list of a "Model".

        Selects the appropriate constructor based on a passed value.

        :param value: a Model field value, returned untouched for non relation fields.
        :type value: Any
        :param child: a child Model to register
        :type child: Union["Model", "NewBaseModel"]
        :param to_register: flag if the relation should be set in RelationshipManager
        :type to_register: bool
        :return: returns a Model or a list of Models
        :rtype: Optional[Union["Model", list["Model"]]]
        """
        if value is None:
            return [] if self.kind.many else None
        # Fast path: ``value`` is already a Model of ``self.to``. Dominant
        # case in row materialization and in user kwargs that pass
        # constructed Models directly. Skips the dispatch table and the
        # ``_register_existing_model`` indirection entirely.
        if value.__class__ is self.to:
            if to_register:
                self.register_relation(model=value, child=cast("Model", child))
            return value
        if value.__class__ is list and self.kind.holds_columns:
            # a key of several columns given as a JSON list
            value = tuple(value)
        return self._constructor_dispatch.get(
            value.__class__.__name__, self._construct_model_from_pk
        )(value, child, to_register)

    def get_relation_name(self) -> str:  # pragma: no cover
        """
        Returns name of the relation, which can be a own name or through model
        names for m2m models

        :return: result of the check
        :rtype: bool
        """
        return self.name

kind property

Returns:

Type Description
RelationKind

forward or reverse side of a foreign key or one-to-one relation

Columns connecting the owner's table to the table of the related model, built once per owner and target: a field copied to another model (inheritance) or re-targeted (forward refs) builds its own link.

Returns:

Type Description
RelationLink

link from the owner to the related model

A foreign key links its own column to the target's primary key, a reverse relation is the mirror of the foreign key it was created from.

Returns:

Type Description
RelationLink

link from the owner to the related model

Source code in ormar/fields/foreign_key.py
Python
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
def build_link(self) -> RelationLink:
    """
    A foreign key links its own column to the target's primary key, a
    reverse relation is the mirror of the foreign key it was created from.

    :return: link from the owner to the related model
    :rtype: RelationLink
    """
    if self.virtual:
        forward = self.to.ormar_config.model_fields[self.get_related_name()]
        return cast("ForeignKeyField", forward).link.mirrored()
    columns = referenced_columns(to=self.to, to_field=self.to_field)
    return RelationLink(
        source=self.owner,
        target=self.to,
        pairs=tuple(
            ColumnPair(
                source_field=self.name,
                source_column=self.local_column(
                    target_column=column, several=len(columns) > 1
                ),
                target_field=field,
                target_column=column,
            )
            for column, field in columns.items()
        ),
    )

column_aliases()

Returns:

Type Description
tuple[str, ...]

the owner's column names of the foreign key

Source code in ormar/fields/foreign_key.py
Python
745
746
747
748
749
750
751
752
def column_aliases(self) -> tuple[str, ...]:
    """
    :return: the owner's column names of the foreign key
    :rtype: tuple[str, ...]
    """
    if self.virtual or self.has_unresolved_forward_refs():
        return (self.get_alias(),)
    return self.link.source_columns()

construct_constraints()

Build the SQLAlchemy foreign keys of the field's column from its link, one per column pair, named foreign_key_name or fk_<owner table>_<target table>_<target column>_<field name>. Built on every call, as SQLAlchemy binds a ForeignKey to one table and subclasses need their own.

Returns:

Type Description
list

SQLAlchemy foreign keys, empty until the target is resolved

Source code in ormar/fields/foreign_key.py
Python
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
def construct_constraints(self) -> list:
    """
    Build the SQLAlchemy foreign keys of the field's column from its link,
    one per column pair, named ``foreign_key_name`` or
    ``fk_<owner table>_<target table>_<target column>_<field name>``.
    Built on every call, as SQLAlchemy binds a ForeignKey to one table and
    subclasses need their own.

    :return: SQLAlchemy foreign keys, empty until the target is resolved
    :rtype: list
    """
    if (
        self.virtual
        or not self.db_constraint
        or self.has_unresolved_forward_refs()
        or self.owner.ormar_config.view
    ):
        return []
    owner_table = self.owner.ormar_config.tablename
    target_table = self.to.ormar_config.tablename
    return [
        sqlalchemy.ForeignKey(
            column=qualified_fk_reference(
                target=self.to, column_alias=pair.target_column
            ),
            ondelete=self.ondelete,
            onupdate=self.onupdate,
            name=self.foreign_key_name
            or f"fk_{owner_table}_{target_table}_{pair.target_column}_{self.name}",
        )
        for pair in self.link.pairs
    ]

construct_key_only_model(value)

Takes a key value and creates an instance of the related model with only the key populated, without registering it on any side.

Parameters:

Name Type Description Default
value Any

value of a related pk / fk column

required

Returns:

Type Description
Model

related model with only pk set

Raises:

Type Description
RelationshipInstanceError

if value does not match the pk type

Source code in ormar/fields/foreign_key.py
Python
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
def construct_key_only_model(self, value: Any) -> "Model":
    """
    Takes a key value and creates an instance of the related model with
    only the key populated, without registering it on any side.

    :param value: value of a related pk / fk column
    :type value: Any
    :raises RelationshipInstanceError: if value does not match the pk type
    :return: related model with only pk set
    :rtype: Model
    """
    if isinstance(value, self.to_key_only):
        values = {field: getattr(value, field) for field in self.target_fields()}
        return key_only_instance(target=self.to, values=values)
    value_type = self.target_value_type()
    if value_type == uuid.UUID and isinstance(value, str):  # pragma: nocover
        value = uuid.UUID(value)
    if not isinstance(value, value_type):
        raise RelationshipInstanceError(
            f"Relationship error - ForeignKey {self.to.__name__} "
            f"is of type {value_type} "
            f"while {type(value)} passed as a parameter."
        )
    return key_only_instance(target=self.to, values=self.target_values(value=value))

construct_table_constraints()

Returns:

Type Description
list

the table-level items of a foreign key of several columns: its FOREIGN KEY (a, b) REFERENCES t (x, y), and a composite unique constraint / index when the field is unique / indexed; empty for other fields

Source code in ormar/fields/foreign_key.py
Python
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
def construct_table_constraints(self) -> list:
    """
    :return: the table-level items of a foreign key of several columns:
        its ``FOREIGN KEY (a, b) REFERENCES t (x, y)``, and a composite
        unique constraint / index when the field is unique / indexed;
        empty for other fields
    :rtype: list
    """
    if (
        not self.kind.holds_columns
        or self.has_unresolved_forward_refs()
        or self.owner.ormar_config.view
    ):
        return []
    pairs = self.link.pairs
    if len(pairs) == 1:
        return []
    columns = [pair.source_column for pair in pairs]
    owner_table = self.owner.ormar_config.tablename
    target_table = self.to.ormar_config.tablename
    items: list = []
    if self.db_constraint:
        items.append(
            sqlalchemy.ForeignKeyConstraint(
                columns=columns,
                refcolumns=[
                    qualified_fk_reference(
                        target=self.to, column_alias=pair.target_column
                    )
                    for pair in pairs
                ],
                ondelete=self.ondelete,
                onupdate=self.onupdate,
                name=self.foreign_key_name
                or f"fk_{owner_table}_{target_table}_{self.name}",
            )
        )
    if self.unique:
        items.append(
            sqlalchemy.UniqueConstraint(
                *columns, name=f"uc_{owner_table}_{self.name}"
            )
        )
    if self.index:
        items.append(sqlalchemy.Index(f"ix_{owner_table}_{self.name}", *columns))
    return items

default_source_field_name()

Returns default target model name on through model.

Returns:

Type Description
str

name of the field

Source code in ormar/fields/foreign_key.py
Python
634
635
636
637
638
639
640
641
def default_source_field_name(self) -> str:
    """
    Returns default target model name on through model.
    :return: name of the field
    :rtype: str
    """
    prefix = "to_" if self.self_reference else ""
    return self.through_relation_name or f"{prefix}{self.owner.get_name()}"

default_target_field_name()

Returns default target model name on through model.

Returns:

Type Description
str

name of the field

Source code in ormar/fields/foreign_key.py
Python
625
626
627
628
629
630
631
632
def default_target_field_name(self) -> str:
    """
    Returns default target model name on through model.
    :return: name of the field
    :rtype: str
    """
    prefix = "from_" if self.self_reference else ""
    return self.through_reverse_relation_name or f"{prefix}{self.to.get_name()}"

evaluate_forward_ref(globalns, localns)

Evaluates the ForwardRef to actual Field based on global and local namespaces

Parameters:

Name Type Description Default
globalns Any

global namespace

required
localns Any

local namespace

required

Returns:

Type Description
None

None

Source code in ormar/fields/foreign_key.py
Python
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
def evaluate_forward_ref(self, globalns: Any, localns: Any) -> None:
    """
    Evaluates the ForwardRef to actual Field based on global and local namespaces

    :param globalns: global namespace
    :type globalns: Any
    :param localns: local namespace
    :type localns: Any
    :return: None
    :rtype: None
    """
    if self.to.__class__ == ForwardRef:
        self._evaluate_forward_ref(globalns, localns)
        validate_view_target(
            to=self.to, virtual=self.virtual, db_constraint=self.db_constraint
        )
        params = populate_fk_params_based_on_to_model(
            to=self.to,
            nullable=self.nullable,
            virtual=self.virtual,
            to_field=self.to_field,
        )
        if not self.virtual:
            validate_link_columns(
                to=self.to,
                to_field=self.to_field,
                columns=self.columns,
                name=self.db_alias,
            )
        self.__type__ = params.annotation
        self.column_type = params.column_type
        self.to_key_only = params.key_only_model

expand_relationship(value, child, to_register=True)

For relations the child model is first constructed (if needed), registered in relation and returned. For relation fields the value can be a pk value (Any type of field), dict (from Model) or actual instance/list of a "Model".

Selects the appropriate constructor based on a passed value.

Parameters:

Name Type Description Default
value Any

a Model field value, returned untouched for non relation fields.

required
child Union[Model, NewBaseModel]

a child Model to register

required
to_register bool

flag if the relation should be set in RelationshipManager

True

Returns:

Type Description
Optional[Union["Model", list["Model"]]]

returns a Model or a list of Models

Source code in ormar/fields/foreign_key.py
Python
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
def expand_relationship(
    self,
    value: Any,
    child: Union["Model", "NewBaseModel"],
    to_register: bool = True,
) -> Optional[Union["Model", list["Model"]]]:
    """
    For relations the child model is first constructed (if needed),
    registered in relation and returned.
    For relation fields the value can be a pk value (Any type of field),
    dict (from Model) or actual instance/list of a "Model".

    Selects the appropriate constructor based on a passed value.

    :param value: a Model field value, returned untouched for non relation fields.
    :type value: Any
    :param child: a child Model to register
    :type child: Union["Model", "NewBaseModel"]
    :param to_register: flag if the relation should be set in RelationshipManager
    :type to_register: bool
    :return: returns a Model or a list of Models
    :rtype: Optional[Union["Model", list["Model"]]]
    """
    if value is None:
        return [] if self.kind.many else None
    # Fast path: ``value`` is already a Model of ``self.to``. Dominant
    # case in row materialization and in user kwargs that pass
    # constructed Models directly. Skips the dispatch table and the
    # ``_register_existing_model`` indirection entirely.
    if value.__class__ is self.to:
        if to_register:
            self.register_relation(model=value, child=cast("Model", child))
        return value
    if value.__class__ is list and self.kind.holds_columns:
        # a key of several columns given as a JSON list
        value = tuple(value)
    return self._constructor_dispatch.get(
        value.__class__.__name__, self._construct_model_from_pk
    )(value, child, to_register)

flat_columns()

Returns:

Type Description
tuple[str, ...]

columns of the related model holding flat_fields

Source code in ormar/fields/foreign_key.py
Python
1011
1012
1013
1014
1015
1016
1017
1018
def flat_columns(self) -> tuple[str, ...]:
    """
    :return: columns of the related model holding ``flat_fields``
    :rtype: tuple[str, ...]
    """
    if not self.kind.holds_columns:
        return self.to.ormar_config.pk.column_aliases()
    return self.link.target_columns()

flat_fields()

Returns:

Type Description
tuple[str, ...]

fields of a related model that represent it in flattened output: the referenced fields of a foreign key, the primary key of a reverse or many-to-many relation

Source code in ormar/fields/foreign_key.py
Python
976
977
978
979
980
981
982
983
984
985
def flat_fields(self) -> tuple[str, ...]:
    """
    :return: fields of a related model that represent it in flattened
        output: the referenced fields of a foreign key, the primary key
        of a reverse or many-to-many relation
    :rtype: tuple[str, ...]
    """
    if not self.kind.holds_columns:
        return self.to.ormar_config.pk.fields
    return self.target_fields()

flat_from_columns(values)

Build the flattened representation of a related model (see flat_value) out of the values of its flat_columns.

Parameters:

Name Type Description Default
values dict[str, Any]

values of the related model's columns by column name

required

Returns:

Type Description
Any

the referenced value, a dict of them for several fields

Source code in ormar/fields/foreign_key.py
Python
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
def flat_from_columns(self, values: dict[str, Any]) -> Any:
    """
    Build the flattened representation of a related model (see
    ``flat_value``) out of the values of its ``flat_columns``.

    :param values: values of the related model's columns by column name
    :type values: dict[str, Any]
    :return: the referenced value, a dict of them for several fields
    :rtype: Any
    """
    fields = self.flat_fields()
    flat = {
        field: flat_field_from_columns(model=self.to, field=field, values=values)
        for field in fields
    }
    return flat[fields[0]] if len(fields) == 1 else flat

flat_value(related)

Represent a related model in flattened output (flatten_fields)::

Text Only
1
2
3
4
Track.album -> 4
Address.country (to_field="iso_code") -> "PL"
OrderLine.order (two columns) -> {"tenant_id": 1, "number": 7}
Shift.membership -> {"tenant_id": 1, "member": {...}, "team": {...}}

A referenced field that is itself a relation (a key holding a foreign key) is represented by its own flattened value.

Parameters:

Name Type Description Default
related Model

related model

required

Returns:

Type Description
Any

the referenced value, a dict of them for several fields

Source code in ormar/fields/foreign_key.py
Python
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
def flat_value(self, related: "Model") -> Any:
    """
    Represent a related model in flattened output (``flatten_fields``)::

        Track.album -> 4
        Address.country (to_field="iso_code") -> "PL"
        OrderLine.order (two columns) -> {"tenant_id": 1, "number": 7}
        Shift.membership -> {"tenant_id": 1, "member": {...}, "team": {...}}

    A referenced field that is itself a relation (a key holding a foreign
    key) is represented by its own flattened value.

    :param related: related model
    :type related: Model
    :return: the referenced value, a dict of them for several fields
    :rtype: Any
    """
    return self.flat_from_columns(
        values={
            column: column_value(model=self.to, data=related, column=column)
            for column in self.flat_columns()
        }
    )

flat_value_type()

Returns:

Type Description
Any

python type of a flattened related model (see flat_value)

Source code in ormar/fields/foreign_key.py
Python
1037
1038
1039
1040
1041
1042
1043
1044
1045
def flat_value_type(self) -> Any:
    """
    :return: python type of a flattened related model (see ``flat_value``)
    :rtype: Any
    """
    fields = self.flat_fields()
    if len(fields) > 1:
        return key_dict_type(target=self.to, fields=fields)
    return flat_field_type(model=self.to, field=fields[0])

get_columns()

Returns:

Type Description
list[sqlalchemy.Column]

the owner's columns of the foreign key, one per referenced column (a placeholder single column until a forward reference is resolved)

Source code in ormar/fields/foreign_key.py
Python
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
def get_columns(self) -> list[sqlalchemy.Column]:
    """
    :return: the owner's columns of the foreign key, one per referenced
        column (a placeholder single column until a forward reference is
        resolved)
    :rtype: list[sqlalchemy.Column]
    """
    if self.has_unresolved_forward_refs():
        return [self.get_column(self.get_alias())]
    pairs = self.link.pairs
    if len(pairs) == 1:
        return [self.get_column(pairs[0].source_column)]
    return [
        sqlalchemy.Column(
            name=pair.source_column,
            type_=column_type(
                model=self.to, field=pair.target_field, column=pair.target_column
            ),
            nullable=self.sql_nullable,
            primary_key=self.primary_key,
            autoincrement=False,
        )
        for pair in pairs
    ]

Returns name to use for reverse relation. It's either set as related_name or by default it's owner model. get_name + 's'

Returns:

Type Description
str

name of the related_name or default related name.

Source code in ormar/fields/foreign_key.py
Python
615
616
617
618
619
620
621
622
623
def get_related_name(self) -> str:
    """
    Returns name to use for reverse relation.
    It's either set as `related_name` or by default it's owner model. get_name + 's'
    :return: name of the related_name or default related name.
    :rtype: str
    """
    suffix = "" if self.one_to_one else "s"
    return self.related_name or self.owner.get_name() + suffix

get_relation_name()

Returns name of the relation, which can be a own name or through model names for m2m models

Returns:

Type Description
bool

result of the check

Source code in ormar/fields/foreign_key.py
Python
1154
1155
1156
1157
1158
1159
1160
1161
1162
def get_relation_name(self) -> str:  # pragma: no cover
    """
    Returns name of the relation, which can be a own name or through model
    names for m2m models

    :return: result of the check
    :rtype: bool
    """
    return self.name

has_unresolved_forward_refs()

Verifies if the filed has any ForwardRefs that require updating before the model can be used.

Returns:

Type Description
bool

result of the check

Source code in ormar/fields/foreign_key.py
Python
1087
1088
1089
1090
1091
1092
1093
1094
1095
def has_unresolved_forward_refs(self) -> bool:
    """
    Verifies if the filed has any ForwardRefs that require updating before the
    model can be used.

    :return: result of the check
    :rtype: bool
    """
    return self.to.__class__ == ForwardRef

local_column(target_column, several)

Parameters:

Name Type Description Default
target_column str

referenced column of the related model's table

required
several bool

whether the foreign key references several columns

required

Returns:

Type Description
str

name of the owner's column storing it: from columns=, the field's own column for a single-column key, or <field>_<referenced column> for keys of several columns

Source code in ormar/fields/foreign_key.py
Python
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
def local_column(self, target_column: str, several: bool) -> str:
    """
    :param target_column: referenced column of the related model's table
    :type target_column: str
    :param several: whether the foreign key references several columns
    :type several: bool
    :return: name of the owner's column storing it: from ``columns=``, the
        field's own column for a single-column key, or
        ``<field>_<referenced column>`` for keys of several columns
    :rtype: str
    """
    if self.columns is not None:
        return self.columns[target_column]
    if not several:
        return self.get_alias()
    return f"{self.name}_{target_column}"

register_relation(model, child)

Registers relation between parent and child in relation manager. Relation manager is kep on each model (different instance).

Used in Metaclass and sometimes some relations are missing (i.e. cloned Models in fastapi might miss one).

Parameters:

Name Type Description Default
model Model

parent model (with relation definition)

required
child Model

child model

required
Source code in ormar/fields/foreign_key.py
Python
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
def register_relation(self, model: "Model", child: "Model") -> None:
    """
    Registers relation between parent and child in relation manager.
    Relation manager is kep on each model (different instance).

    Used in Metaclass and sometimes some relations are missing
    (i.e. cloned Models in fastapi might miss one).

    :param model: parent model (with relation definition)
    :type model: Model class
    :param child: child model
    :type child: Model class
    """
    model._orm.add(parent=model, child=child, field=self)

target_fields()

Returns:

Type Description
tuple[str, ...]

fields of the related model the foreign key references: its to_field or its primary key fields

Source code in ormar/fields/foreign_key.py
Python
692
693
694
695
696
697
698
699
700
701
def target_fields(self) -> tuple[str, ...]:
    """
    :return: fields of the related model the foreign key references: its
        ``to_field`` or its primary key fields
    :rtype: tuple[str, ...]
    """
    names = to_field_names(to_field=self.to_field)
    if names is not None:
        return names
    return self.to.ormar_config.pk.fields

target_value_of(related)

Parameters:

Name Type Description Default
related Any

related model, its key-only model, a dict of its fields or a raw value

required

Returns:

Type Description
Any

the value this foreign key stores for it, None when the related model lacks it

Source code in ormar/fields/foreign_key.py
Python
965
966
967
968
969
970
971
972
973
974
def target_value_of(self, related: Any) -> Any:
    """
    :param related: related model, its key-only model, a dict of its
        fields or a raw value
    :type related: Any
    :return: the value this foreign key stores for it, ``None`` when the
        related model lacks it
    :rtype: Any
    """
    return self.link.values_for(related=related)[self.name]

target_value_type()

Returns:

Type Description
Any

python type of a raw value of the relation: the to_field type or the related model's key type

Source code in ormar/fields/foreign_key.py
Python
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
def target_value_type(self) -> Any:
    """
    :return: python type of a raw value of the relation: the ``to_field``
        type or the related model's key type
    :rtype: Any
    """
    names = to_field_names(to_field=self.to_field)
    if names is None:
        return self.to.ormar_config.pk.python_type()
    if len(names) == 1:
        return self.to.ormar_config.model_fields[names[0]].__type__
    return tuple

target_values(value)

Parameters:

Name Type Description Default
value Any

raw value of the relation

required

Returns:

Type Description
dict[str, Any]

the value split into the referenced fields of the related model

Source code in ormar/fields/foreign_key.py
Python
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
def target_values(self, value: Any) -> dict[str, Any]:
    """
    :param value: raw value of the relation
    :type value: Any
    :return: the value split into the referenced fields of the related model
    :rtype: dict[str, Any]
    """
    names = to_field_names(to_field=self.to_field)
    if names is None:
        return self.to.ormar_config.pk.to_dict(value=value)
    return dict(zip(names, key_parts(value=value, size=len(names))))

Greatest

Bases: Function

The largest of the arguments. PostgreSQL ignores NULL arguments, MySQL and SQLite return NULL when any argument is NULL.

Source code in ormar/queryset/expressions.py
Python
167
168
169
170
171
172
173
class Greatest(Function):
    """
    The largest of the arguments. PostgreSQL ignores ``NULL`` arguments,
    MySQL and SQLite return ``NULL`` when any argument is ``NULL``.
    """

    _sql_name = "greatest"

IndexColumns

Bases: Index

Subclass of sqlalchemy.Index. Used to avoid importing anything from sqlalchemy by user.

Passing unique=True together with case_insensitive=True builds a case-insensitive unique index by wrapping each named column in LOWER(), which is how case-insensitive uniqueness is expressed (a regular UniqueConstraint cannot hold SQL expressions).

Source code in ormar/fields/constraints.py
Python
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
class IndexColumns(Index):
    """
    Subclass of sqlalchemy.Index.
    Used to avoid importing anything from sqlalchemy by user.

    Passing ``unique=True`` together with ``case_insensitive=True`` builds a
    case-insensitive unique index by wrapping each named column in ``LOWER()``,
    which is how case-insensitive uniqueness is expressed (a regular
    UniqueConstraint cannot hold SQL expressions).
    """

    def __init__(
        self,
        *args: Any,
        name: Optional[str] = None,
        case_insensitive: bool = False,
        **kw: Any,
    ) -> None:
        """
        :param args: column names, or SQL expressions for a functional index
        :type args: Any
        :param name: optional explicit index name
        :type name: Optional[str]
        :param case_insensitive: wrap each named column in ``LOWER()`` so the
            index (and its uniqueness, when ``unique=True``) ignores case
        :type case_insensitive: bool
        :param kw: additional keyword arguments passed to sqlalchemy.Index
        :type kw: Any
        """
        if case_insensitive:
            args = tuple(func.lower(column(arg)) for arg in args)
        if not name:
            name = "TEMPORARY_NAME"
        super().__init__(name, *args, **kw)

__init__(*args, name=None, case_insensitive=False, **kw)

Parameters:

Name Type Description Default
args Any

column names, or SQL expressions for a functional index

()
name Optional[str]

optional explicit index name

None
case_insensitive bool

wrap each named column in LOWER() so the index (and its uniqueness, when unique=True) ignores case

False
kw Any

additional keyword arguments passed to sqlalchemy.Index

{}
Source code in ormar/fields/constraints.py
Python
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
def __init__(
    self,
    *args: Any,
    name: Optional[str] = None,
    case_insensitive: bool = False,
    **kw: Any,
) -> None:
    """
    :param args: column names, or SQL expressions for a functional index
    :type args: Any
    :param name: optional explicit index name
    :type name: Optional[str]
    :param case_insensitive: wrap each named column in ``LOWER()`` so the
        index (and its uniqueness, when ``unique=True``) ignores case
    :type case_insensitive: bool
    :param kw: additional keyword arguments passed to sqlalchemy.Index
    :type kw: Any
    """
    if case_insensitive:
        args = tuple(func.lower(column(arg)) for arg in args)
    if not name:
        name = "TEMPORARY_NAME"
    super().__init__(name, *args, **kw)

Inserted

Bases: Expression

Value a conflicting insert tried to write into a field, only in update_values of create() / bulk_create() with on_conflict="update": excluded.<column> on PostgreSQL and SQLite, VALUES(<column>) on MySQL. F() there is the existing row's column.

Source code in ormar/queryset/expressions.py
Python
100
101
102
103
104
105
106
107
108
109
110
111
112
113
class Inserted(Expression):
    """
    Value a conflicting insert tried to write into a field, only in
    ``update_values`` of ``create()`` / ``bulk_create()`` with
    ``on_conflict="update"``: ``excluded.<column>`` on PostgreSQL and SQLite,
    ``VALUES(<column>)`` on MySQL. ``F()`` there is the existing row's column.
    """

    def __init__(self, path: str) -> None:
        """
        :param path: name of a non-relation field of the inserted model
        :type path: str
        """
        self._path = path

__init__(path)

Parameters:

Name Type Description Default
path str

name of a non-relation field of the inserted model

required
Source code in ormar/queryset/expressions.py
Python
108
109
110
111
112
113
def __init__(self, path: str) -> None:
    """
    :param path: name of a non-relation field of the inserted model
    :type path: str
    """
    self._path = path

Integer

Bases: ModelFieldFactory, int

Integer field factory that construct Field classes and populated their values.

Source code in ormar/fields/model_fields.py
Python
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
class Integer(ModelFieldFactory, int):
    """
    Integer field factory that construct Field classes and populated their values.
    """

    _bases = (IntegerField,)
    _type = int
    _sample = 0

    def __new__(  # type: ignore
        cls,
        *,
        minimum: Optional[int] = None,
        maximum: Optional[int] = None,
        multiple_of: Optional[int] = None,
        unsigned: bool = False,
        **kwargs: Any,
    ) -> Self:
        if unsigned and minimum is None:
            minimum = 0
        autoincrement = kwargs.pop("autoincrement", None)
        autoincrement_explicit = autoincrement is not None
        autoincrement = (
            autoincrement
            if autoincrement is not None
            else kwargs.get("primary_key", False)
        )
        kwargs = {
            **kwargs,
            **{
                k: v
                for k, v in locals().items()
                if k not in ["cls", "__class__", "kwargs"]
            },
        }
        kwargs["ge"] = kwargs["minimum"]
        kwargs["le"] = kwargs["maximum"]
        return super().__new__(cls, **kwargs)

    @classmethod
    def get_column_type(cls, **kwargs: Any) -> Any:
        """
        Return proper type of db column for given field type.
        Accepts required and optional parameters that each column type accepts.

        :param kwargs: key, value pairs of sqlalchemy options
        :type kwargs: Any
        :return: initialized column with proper options
        :rtype: sqlalchemy Column
        """
        return unsigned_on_mysql(
            sqlalchemy.Integer(), mysql.INTEGER, kwargs.get("unsigned", False)
        )

get_column_type(**kwargs) classmethod

Return proper type of db column for given field type. Accepts required and optional parameters that each column type accepts.

Parameters:

Name Type Description Default
kwargs Any

key, value pairs of sqlalchemy options

{}

Returns:

Type Description
sqlalchemy Column

initialized column with proper options

Source code in ormar/fields/model_fields.py
Python
316
317
318
319
320
321
322
323
324
325
326
327
328
329
@classmethod
def get_column_type(cls, **kwargs: Any) -> Any:
    """
    Return proper type of db column for given field type.
    Accepts required and optional parameters that each column type accepts.

    :param kwargs: key, value pairs of sqlalchemy options
    :type kwargs: Any
    :return: initialized column with proper options
    :rtype: sqlalchemy Column
    """
    return unsigned_on_mysql(
        sqlalchemy.Integer(), mysql.INTEGER, kwargs.get("unsigned", False)
    )

JSON

Bases: ModelFieldFactory, Json

JSON field factory that construct Field classes and populated their values.

Source code in ormar/fields/model_fields.py
Python
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
class JSON(ModelFieldFactory, pydantic.Json):
    """
    JSON field factory that construct Field classes and populated their values.
    """

    _type = pydantic.Json
    _sample = '{"json": "json"}'

    @classmethod
    def get_column_type(cls, **kwargs: Any) -> Any:
        """
        Return proper type of db column for given field type.
        Accepts required and optional parameters that each column type accepts.

        :param kwargs: key, value pairs of sqlalchemy options
        :type kwargs: Any
        :return: initialized column with proper options
        :rtype: sqlalchemy Column
        """
        return sqlalchemy.JSON(none_as_null=kwargs.get("sql_nullable", False))

get_column_type(**kwargs) classmethod

Return proper type of db column for given field type. Accepts required and optional parameters that each column type accepts.

Parameters:

Name Type Description Default
kwargs Any

key, value pairs of sqlalchemy options

{}

Returns:

Type Description
sqlalchemy Column

initialized column with proper options

Source code in ormar/fields/model_fields.py
Python
529
530
531
532
533
534
535
536
537
538
539
540
@classmethod
def get_column_type(cls, **kwargs: Any) -> Any:
    """
    Return proper type of db column for given field type.
    Accepts required and optional parameters that each column type accepts.

    :param kwargs: key, value pairs of sqlalchemy options
    :type kwargs: Any
    :return: initialized column with proper options
    :rtype: sqlalchemy Column
    """
    return sqlalchemy.JSON(none_as_null=kwargs.get("sql_nullable", False))

LargeBinary

Bases: ModelFieldFactory, bytes

LargeBinary field factory that construct Field classes and populated their values.

Source code in ormar/fields/model_fields.py
Python
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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
class LargeBinary(ModelFieldFactory, bytes):
    """
    LargeBinary field factory that construct Field classes
    and populated their values.
    """

    _type = bytes
    _sample = "bytes"

    def __new__(  # type: ignore # noqa CFQ002
        cls, *, max_length: int, represent_as_base64_str: bool = False, **kwargs: Any
    ) -> Self:  # type: ignore
        kwargs = {
            **kwargs,
            **{
                k: v
                for k, v in locals().items()
                if k not in ["cls", "__class__", "kwargs"]
            },
        }
        return super().__new__(cls, **kwargs)

    @classmethod
    def get_column_type(cls, **kwargs: Any) -> Any:
        """
        Return proper type of db column for given field type.
        Accepts required and optional parameters that each column type accepts.

        :param kwargs: key, value pairs of sqlalchemy options
        :type kwargs: Any
        :return: initialized column with proper options
        :rtype: sqlalchemy Column
        """
        return sqlalchemy.LargeBinary(length=kwargs.get("max_length"))

    @classmethod
    def validate(cls, **kwargs: Any) -> None:
        """
        Used to validate if all required parameters on a given field type are set.
        :param kwargs: all params passed during construction
        :type kwargs: Any
        """
        max_length = kwargs.get("max_length", None)
        if max_length <= 0:
            raise ModelDefinitionError(
                "Parameter max_length is required for field LargeBinary"
            )

get_column_type(**kwargs) classmethod

Return proper type of db column for given field type. Accepts required and optional parameters that each column type accepts.

Parameters:

Name Type Description Default
kwargs Any

key, value pairs of sqlalchemy options

{}

Returns:

Type Description
sqlalchemy Column

initialized column with proper options

Source code in ormar/fields/model_fields.py
Python
565
566
567
568
569
570
571
572
573
574
575
576
@classmethod
def get_column_type(cls, **kwargs: Any) -> Any:
    """
    Return proper type of db column for given field type.
    Accepts required and optional parameters that each column type accepts.

    :param kwargs: key, value pairs of sqlalchemy options
    :type kwargs: Any
    :return: initialized column with proper options
    :rtype: sqlalchemy Column
    """
    return sqlalchemy.LargeBinary(length=kwargs.get("max_length"))

validate(**kwargs) classmethod

Used to validate if all required parameters on a given field type are set.

Parameters:

Name Type Description Default
kwargs Any

all params passed during construction

{}
Source code in ormar/fields/model_fields.py
Python
578
579
580
581
582
583
584
585
586
587
588
589
@classmethod
def validate(cls, **kwargs: Any) -> None:
    """
    Used to validate if all required parameters on a given field type are set.
    :param kwargs: all params passed during construction
    :type kwargs: Any
    """
    max_length = kwargs.get("max_length", None)
    if max_length <= 0:
        raise ModelDefinitionError(
            "Parameter max_length is required for field LargeBinary"
        )

Least

Bases: Function

The smallest of the arguments. PostgreSQL ignores NULL arguments, MySQL and SQLite return NULL when any argument is NULL.

Source code in ormar/queryset/expressions.py
Python
176
177
178
179
180
181
182
class Least(Function):
    """
    The smallest of the arguments. PostgreSQL ignores ``NULL`` arguments,
    MySQL and SQLite return ``NULL`` when any argument is ``NULL``.
    """

    _sql_name = "least"

ManyToManyField

Bases: ForeignKeyField, QuerySetProtocol, RelationProtocol

Actual class returned from ManyToMany function call and stored in model_fields.

Source code in ormar/fields/many_to_many.py
Python
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
class ManyToManyField(  # type: ignore
    ForeignKeyField,
    ormar.QuerySetProtocol,
    ormar.RelationProtocol,
):
    """
    Actual class returned from ManyToMany function call and stored in model_fields.
    """

    def __init__(self, **kwargs: Any) -> None:
        if TYPE_CHECKING:  # pragma: no cover
            self.__type__: type
            self.to: type["Model"]
            self.through: type["Model"]
        super().__init__(**kwargs)

    @property
    def kind(self) -> RelationKind:
        """
        :return: ``MANY_TO_MANY``, for both sides of the relation
        :rtype: RelationKind
        """
        return MANY_TO_MANY

    def has_unresolved_forward_refs(self) -> bool:
        """
        Verifies if the filed has any ForwardRefs that require updating before the
        model can be used.

        :return: result of the check
        :rtype: bool
        """
        return self.to.__class__ == ForwardRef or self.through.__class__ == ForwardRef

    def evaluate_forward_ref(self, globalns: Any, localns: Any) -> None:
        """
        Evaluates the ForwardRef to actual Field based on global and local namespaces

        :param globalns: global namespace
        :type globalns: Any
        :param localns: local namespace
        :type localns: Any
        :return: None
        :rtype: None
        """
        if self.to.__class__ == ForwardRef:
            self._evaluate_forward_ref(globalns, localns)
            (
                self.__type__,
                self.column_type,
                pk_only_model,
            ) = populate_m2m_params_based_on_to_model(
                to=self.to, nullable=self.nullable
            )
            self.to_key_only = pk_only_model

        if self.through.__class__ == ForwardRef:
            self._evaluate_forward_ref(globalns, localns, is_through=True)

    def get_relation_name(self) -> str:
        """
        Returns name of the relation, which can be a own name or through model
        names for m2m models

        :return: result of the check
        :rtype: bool
        """
        return self.through_target_field_name()

    def get_filter_clause_target(self) -> type["Model"]:
        return self.through

    def swaps_through_fields(self) -> bool:
        """
        On the primary side of a self-referencing relation the generated
        through field names (``from_<model>`` / ``to_<model>``) are swapped, so
        both sides read the same columns. Explicit ``through_relation_name``
        and ``through_reverse_relation_name`` are used as documented on both
        sides instead (the field leading to the declaring model, and the field
        leading to the related model).

        :return: whether the owner and target through fields are swapped
        :rtype: bool
        """
        explicit = bool(
            self.through_relation_name and self.through_reverse_relation_name
        )
        return (
            self.self_reference
            and self.self_reference_primary == self.name
            and not explicit
        )

    def through_owner_field_name(self) -> str:
        """
        :return: name of the through model field pointing back to the owner
            (for self-referencing relations depends on which side this is)
        :rtype: str
        """
        if self.swaps_through_fields():
            return self.default_target_field_name()
        return self.default_source_field_name()

    def through_target_field_name(self) -> str:
        """
        :return: name of the through model field pointing to the related model
        :rtype: str
        """
        if self.swaps_through_fields():
            return self.default_source_field_name()
        return self.default_target_field_name()

    def build_link(self) -> RelationLink:
        """
        Columns connecting the owner's table to the through table: the mirror
        of the through model's foreign key to the owner. The second hop, from
        the through table to the related model, is the link of the through
        model's field named ``through_target_field_name()``.

        :return: link from the owner to the through model
        :rtype: RelationLink
        """
        through_field = self.through.ormar_config.model_fields[
            self.through_owner_field_name()
        ]
        return cast("ForeignKeyField", through_field).link.mirrored()

    def create_default_through_model(self) -> None:
        """
        Creates default empty through model if no additional fields are required.
        """
        owner_name = self.owner.get_name(lower=False)
        to_name = self.to.get_name(lower=False)
        class_name = f"{owner_name}{to_name}"
        table_name = f"{owner_name.lower()}s_{to_name.lower()}s"
        base_namespace = {
            "__module__": self.owner.__module__,
            "__qualname__": f"{self.owner.__qualname__}.{class_name}",
        }
        # Default through tables live in the owner's schema (the side declaring
        # the M2M). User-supplied through models can override by configuring
        # their own OrmarConfig.schema.
        new_config = ormar.models.ormar_config.OrmarConfig(
            tablename=table_name,
            database=self.owner.ormar_config.database,
            metadata=self.owner.ormar_config.metadata,
            schema=self.owner.ormar_config.schema,
        )
        through_model = type(
            class_name,
            (ormar.Model,),
            {
                **base_namespace,
                "ormar_config": new_config,
                "id": ormar.Integer(name="id", primary_key=True),
            },
        )
        self.through = cast(type["Model"], through_model)

kind property

Returns:

Type Description
RelationKind

MANY_TO_MANY, for both sides of the relation

Columns connecting the owner's table to the through table: the mirror of the through model's foreign key to the owner. The second hop, from the through table to the related model, is the link of the through model's field named through_target_field_name().

Returns:

Type Description
RelationLink

link from the owner to the through model

Source code in ormar/fields/many_to_many.py
Python
291
292
293
294
295
296
297
298
299
300
301
302
303
304
def build_link(self) -> RelationLink:
    """
    Columns connecting the owner's table to the through table: the mirror
    of the through model's foreign key to the owner. The second hop, from
    the through table to the related model, is the link of the through
    model's field named ``through_target_field_name()``.

    :return: link from the owner to the through model
    :rtype: RelationLink
    """
    through_field = self.through.ormar_config.model_fields[
        self.through_owner_field_name()
    ]
    return cast("ForeignKeyField", through_field).link.mirrored()

create_default_through_model()

Creates default empty through model if no additional fields are required.

Source code in ormar/fields/many_to_many.py
Python
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
def create_default_through_model(self) -> None:
    """
    Creates default empty through model if no additional fields are required.
    """
    owner_name = self.owner.get_name(lower=False)
    to_name = self.to.get_name(lower=False)
    class_name = f"{owner_name}{to_name}"
    table_name = f"{owner_name.lower()}s_{to_name.lower()}s"
    base_namespace = {
        "__module__": self.owner.__module__,
        "__qualname__": f"{self.owner.__qualname__}.{class_name}",
    }
    # Default through tables live in the owner's schema (the side declaring
    # the M2M). User-supplied through models can override by configuring
    # their own OrmarConfig.schema.
    new_config = ormar.models.ormar_config.OrmarConfig(
        tablename=table_name,
        database=self.owner.ormar_config.database,
        metadata=self.owner.ormar_config.metadata,
        schema=self.owner.ormar_config.schema,
    )
    through_model = type(
        class_name,
        (ormar.Model,),
        {
            **base_namespace,
            "ormar_config": new_config,
            "id": ormar.Integer(name="id", primary_key=True),
        },
    )
    self.through = cast(type["Model"], through_model)

evaluate_forward_ref(globalns, localns)

Evaluates the ForwardRef to actual Field based on global and local namespaces

Parameters:

Name Type Description Default
globalns Any

global namespace

required
localns Any

local namespace

required

Returns:

Type Description
None

None

Source code in ormar/fields/many_to_many.py
Python
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
def evaluate_forward_ref(self, globalns: Any, localns: Any) -> None:
    """
    Evaluates the ForwardRef to actual Field based on global and local namespaces

    :param globalns: global namespace
    :type globalns: Any
    :param localns: local namespace
    :type localns: Any
    :return: None
    :rtype: None
    """
    if self.to.__class__ == ForwardRef:
        self._evaluate_forward_ref(globalns, localns)
        (
            self.__type__,
            self.column_type,
            pk_only_model,
        ) = populate_m2m_params_based_on_to_model(
            to=self.to, nullable=self.nullable
        )
        self.to_key_only = pk_only_model

    if self.through.__class__ == ForwardRef:
        self._evaluate_forward_ref(globalns, localns, is_through=True)

get_relation_name()

Returns name of the relation, which can be a own name or through model names for m2m models

Returns:

Type Description
bool

result of the check

Source code in ormar/fields/many_to_many.py
Python
238
239
240
241
242
243
244
245
246
def get_relation_name(self) -> str:
    """
    Returns name of the relation, which can be a own name or through model
    names for m2m models

    :return: result of the check
    :rtype: bool
    """
    return self.through_target_field_name()

has_unresolved_forward_refs()

Verifies if the filed has any ForwardRefs that require updating before the model can be used.

Returns:

Type Description
bool

result of the check

Source code in ormar/fields/many_to_many.py
Python
203
204
205
206
207
208
209
210
211
def has_unresolved_forward_refs(self) -> bool:
    """
    Verifies if the filed has any ForwardRefs that require updating before the
    model can be used.

    :return: result of the check
    :rtype: bool
    """
    return self.to.__class__ == ForwardRef or self.through.__class__ == ForwardRef

swaps_through_fields()

On the primary side of a self-referencing relation the generated through field names (from_<model> / to_<model>) are swapped, so both sides read the same columns. Explicit through_relation_name and through_reverse_relation_name are used as documented on both sides instead (the field leading to the declaring model, and the field leading to the related model).

Returns:

Type Description
bool

whether the owner and target through fields are swapped

Source code in ormar/fields/many_to_many.py
Python
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
def swaps_through_fields(self) -> bool:
    """
    On the primary side of a self-referencing relation the generated
    through field names (``from_<model>`` / ``to_<model>``) are swapped, so
    both sides read the same columns. Explicit ``through_relation_name``
    and ``through_reverse_relation_name`` are used as documented on both
    sides instead (the field leading to the declaring model, and the field
    leading to the related model).

    :return: whether the owner and target through fields are swapped
    :rtype: bool
    """
    explicit = bool(
        self.through_relation_name and self.through_reverse_relation_name
    )
    return (
        self.self_reference
        and self.self_reference_primary == self.name
        and not explicit
    )

through_owner_field_name()

Returns:

Type Description
str

name of the through model field pointing back to the owner (for self-referencing relations depends on which side this is)

Source code in ormar/fields/many_to_many.py
Python
272
273
274
275
276
277
278
279
280
def through_owner_field_name(self) -> str:
    """
    :return: name of the through model field pointing back to the owner
        (for self-referencing relations depends on which side this is)
    :rtype: str
    """
    if self.swaps_through_fields():
        return self.default_target_field_name()
    return self.default_source_field_name()

through_target_field_name()

Returns:

Type Description
str

name of the through model field pointing to the related model

Source code in ormar/fields/many_to_many.py
Python
282
283
284
285
286
287
288
289
def through_target_field_name(self) -> str:
    """
    :return: name of the through model field pointing to the related model
    :rtype: str
    """
    if self.swaps_through_fields():
        return self.default_source_field_name()
    return self.default_target_field_name()

Model

Bases: ModelRow

Source code in ormar/models/model.py
Python
 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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
class Model(ModelRow):
    __abstract__ = False
    if TYPE_CHECKING:  # pragma nocover
        ormar_config: OrmarConfig

    def __repr__(self) -> str:  # pragma nocover
        _repr = {
            k: getattr(self, k)
            for k, v in self.ormar_config.model_fields.items()
            if not v.skip_field
        }
        return f"{self.__class__.__name__}({str(_repr)})"

    async def _execute_query(
        self,
        expr: Executable,
        is_select: bool = False,
        params: Optional[dict] = None,
    ) -> Any:
        """
        Run a statement of this model: fetch one row of a select, otherwise
        execute the write and return its result (inserted primary key or
        number of changed rows).

        Single-row writes and ``load()`` pass a cached statement template
        (see ``ormar.queryset.templates``) and its values as ``params``.

        :param expr: statement to run
        :type expr: Executable
        :param is_select: fetch one row instead of executing a write
        :type is_select: bool
        :param params: values for named bind parameters of the statement
        :type params: Optional[dict]
        :return: fetched row, inserted primary key or row count
        :rtype: Any
        """
        async with self.ormar_config.database.get_query_executor() as executor:
            row = (
                await executor.fetch_one(query=expr, params=params)
                if is_select
                else await executor.execute(query=expr, params=params)
            )
        return row

    async def _emit_signal(self, name: str, **kwargs: Any) -> None:
        """
        Emit a lifecycle signal on this model's SignalEmitter.

        When ``ormar_config.emit_parent_signals`` is True, the same signal is
        also dispatched on every concrete ormar ancestor in the MRO. Each
        emit uses ``sender=ancestor_cls`` so handlers registered with
        ``@pre_save(Parent)`` see the parent class as the sender.

        :param name: signal name on the SignalEmitter (e.g. ``"pre_save"``).
        :type name: str
        :param kwargs: extra payload forwarded to receivers.
        :type kwargs: Any
        """
        cls = type(self)
        await getattr(self.ormar_config.signals, name).send(sender=cls, **kwargs)
        if not self.ormar_config.emit_parent_signals:
            return
        seen = {id(self.ormar_config.signals)}
        for ancestor in cls.__mro__[1:]:
            cfg = getattr(ancestor, "ormar_config", None)
            if cfg is None or cfg.abstract or id(cfg.signals) in seen:
                continue
            seen.add(id(cfg.signals))
            await getattr(cfg.signals, name).send(sender=ancestor, **kwargs)

    async def upsert(self: T, **kwargs: Any) -> T:
        """
        Performs either a save or an update:

        * a model loaded from or already saved to the database is updated,
        * a model without a primary key is inserted,
        * a model never saved but with its key set (uuid default, natural or
          composite key) is looked up first and updated if the row exists,
          inserted otherwise.

        For save kwargs are ignored, used only in update if provided.
        ``__force_save__`` is accepted for backwards compatibility and ignored.

        :param kwargs: list of fields to update
        :type kwargs: Any
        :return: saved Model
        :rtype: Model
        """
        self.verify_writable()
        kwargs.pop("__force_save__", None)
        if self.persisted:
            return await self.update(**kwargs)
        if self.pk is None:
            return await self.save()
        template = row_template(
            statement=RowSelectWrite, model_cls=type(self), pk=self.pk
        )
        row = await self._execute_query(
            expr=template.statement, is_select=True, params=template.params
        )
        if not row:
            return await self.save()
        return await self.update(_partial=False, **kwargs)

    def _verify_key_parts_set(self, row: dict[str, Any]) -> None:
        """
        Checks that every primary key column the database does not generate
        is set before an insert.

        :raises ModelPersistenceError: if a key part is missing
        :param row: values about to be inserted, by column name
        :type row: dict[str, Any]
        """
        key = self.ormar_config.pk
        if key.autoincrement:
            return
        model_fields = self.ormar_config.model_fields
        missing: list[str] = []
        for column in key.column_aliases():
            owners = [
                name
                for name in self.get_field_names_of_column(column=column)
                if name in key.fields
            ]
            if row.get(column) is None and all(
                model_fields[name].server_default is None for name in owners
            ):
                missing.extend(name for name in owners if name not in missing)
        if missing:
            raise ModelPersistenceError(
                f"{self.__class__.__name__} primary key parts must be set before "
                f"saving: {missing}"
            )

    async def save(self: T) -> T:
        """
        Performs a save of given Model instance.
        If primary key is already saved, db backend will throw integrity error.

        Related models are saved by pk number, reverse relation and many to many fields
        are not saved - use corresponding relations methods.

        If there are fields with server_default set and those fields
        are not already filled save will trigger also a second query
        to refreshed the fields populated server side.

        Does not recognize if model was previously saved.
        If you want to perform update or insert depending on the pk
        fields presence use upsert.

        Sends pre_save and post_save signals.

        Sets model save status to True.

        :return: saved Model
        :rtype: Model
        """
        return cast(T, await self._save())

    async def _save(
        self: T, on_conflict: Optional[Literal["ignore"]] = None
    ) -> Optional[T]:
        """
        Body of ``save()``. With ``on_conflict="ignore"`` a row conflicting with
        an existing one is skipped: ``None`` is returned, ``post_save`` not sent.

        :param on_conflict: ``ignore`` to skip a conflicting row
        :type on_conflict: Optional[Literal["ignore"]]
        :return: saved Model, ``None`` when the row was skipped
        :rtype: Optional[Model]
        """
        self.verify_writable()
        await self._emit_signal("pre_save", instance=self)
        self_fields = self._prepare_insert_row()
        key = self.ormar_config.pk
        # MySQL has no conflict clause telling an insert from a skipped row, so
        # it runs a plain insert and a duplicate key error means skipped
        rules = self.ormar_config.database.rules
        returning = bool(on_conflict) and rules.conflict_returning
        template = insert_template(
            model_cls=type(self),
            values=self_fields,
            on_conflict=on_conflict if returning else None,
            returning=key.column_aliases() if returning else (),
        )
        try:
            pk = await self._execute_query(
                expr=template.statement, is_select=returning, params=template.params
            )
        except IntegrityError as error:
            if not on_conflict or not rules.is_duplicate_key(error=error):
                raise
            return None  # pragma: no cover
        if returning:  # pragma: no cover
            if pk is None:
                return None
            pk = key.getter(keys=key.column_aliases())(pk)

        pk_returned_from_insert = False
        if pk and self.pk is None and isinstance(pk, key.python_type()):
            for field, part in key.to_dict(value=pk).items():
                setattr(self, field, part)
            pk_returned_from_insert = True

        if self.pk is None:
            raise ModelPersistenceError(  # pragma: no cover
                f"Could not recover the generated primary key for "
                f"{self.__class__.__name__} after INSERT. This happens on "
                "backends that lack RETURNING support for server-side "
                "defaults on non-AUTO_INCREMENT primary keys — most notably "
                "Oracle MySQL, which does not implement RETURNING in any "
                "version. Use autoincrement=True, provide the primary key "
                "client-side, or switch to a RETURNING-capable backend "
                "(PostgreSQL, SQLite 3.35+, MariaDB 10.5+)."
            )

        self.set_save_status(True)
        # refresh server-side defaults — but skip the pk if the insert already
        # returned it, so save() stays a single round-trip when the pk is the
        # only server_default field.
        if any(
            field.server_default is not None
            for name, field in self.ormar_config.model_fields.items()
            if name not in self_fields
            and not (pk_returned_from_insert and name in key.fields)
        ):
            await self.load()

        self._reset_change_tracking()
        await self._emit_signal("post_save", instance=self)
        return self

    def _prepare_insert_row(self) -> builtins.dict[str, Any]:
        """
        Fill the default values of the instance and return its row to insert,
        by column name. A generated primary key that is not set is left out.

        :raises ModelPersistenceError: if only a part of the primary key is set
        :return: inserted values by column name
        :rtype: dict[str, Any]
        """
        self_fields = self._extract_model_db_fields()
        key = self.ormar_config.pk
        if not self.pk and key.autoincrement:
            for field in key.fields:
                self_fields.pop(field, None)
        self_fields = self.populate_default_values(self_fields)
        # Values taken from ``__dict__`` are already set, re-assigning them only
        # costs a validation and two hash recomputations per field.
        current_values = self.__dict__
        related_names = self.extract_related_names()
        self.update_from_dict(
            {
                name: value
                for name, value in self_fields.items()
                if name not in related_names
                and name in self.ormar_config.model_fields
                and (name not in current_values or current_values[name] is not value)
            }
        )
        self_fields = self.translate_columns_to_aliases(self_fields)
        self._verify_key_parts_set(row=self_fields)
        return self_fields

    @classmethod
    def _conflict_updates(
        cls,
        update_fields: Optional[list[str]],
        update_values: Optional[builtins.dict[str, Any]],
    ) -> tuple[builtins.dict[str, Any], builtins.dict[str, Any]]:
        """
        Validate the ``update_values`` of an upsert like ``QuerySet.update()``
        validates its values and return the ``on_update`` values of the fields
        set by neither ``update_fields`` nor ``update_values``, and the
        ``update_values`` as column values or expression nodes, both by column
        name.

        :param update_fields: names of the fields updated from the inserted row
        :type update_fields: Optional[list[str]]
        :param update_values: value or expression by field name
        :type update_values: Optional[dict[str, Any]]
        :raises QueryDefinitionError: for a field not stored in the model's
            table (unknown, reverse or many to many relation), a field also in
            ``update_fields``, an expression setting a relation, reading a
            related model or another field the upsert sets
        :return: ``on_update`` values and ``update_values``, by column name
        :rtype: tuple[dict[str, Any], dict[str, Any]]
        """
        update_fields = update_fields or []
        update_values = update_values or {}
        # foreign keys stored in the model's own table, no reverse or m2m names
        related_names = cls._extract_db_related_names()
        unknown = [
            name
            for name in update_values
            if name not in cls.extract_db_own_fields() and name not in related_names
        ]
        if unknown:
            raise QueryDefinitionError(
                f"update_values names fields the model does not store in its "
                f"table: {unknown}"
            )
        repeated = [name for name in update_values if name in update_fields]
        if repeated:
            raise QueryDefinitionError(
                f"Fields cannot be in both update_fields and update_values: {repeated}"
            )
        model_fields = cls.ormar_config.model_fields
        on_update = {
            cls.get_column_alias(field_name=name): model_fields[name].get_on_update()
            for name in sorted(cls._onupdate_fields)
            if name not in update_fields and name not in update_values
        }
        updated = {*update_fields, *update_values, *cls._onupdate_fields}
        expressions = {
            name: value._node()
            for name, value in update_values.items()
            if isinstance(value, Expression)
        }
        for name, node in expressions.items():
            expression_columns(node=node, model=cls, upsert=True)
            read = [
                leaf._path
                for leaf in expression_leaves(node=node)
                if isinstance(leaf, F)
            ]
            if name in related_names or any(
                field != name and field in updated for field in read
            ):
                raise QueryDefinitionError(
                    f"update_values cannot set '{name}' from an expression reading "
                    f"{read}: expressions set no relations and read no fields set "
                    f"by the same upsert (use Inserted() for the inserted value)."
                )
        values = cls.validate_update_values(
            {
                name: value
                for name, value in update_values.items()
                if name not in expressions
            }
        )
        values = cls.reconvert_str_to_bytes(values)
        return on_update, cls.translate_columns_to_aliases({**values, **expressions})

    async def _upsert(
        self: T,
        conflict_target: Optional[list[str]] = None,
        update_fields: Optional[list[str]] = None,
        update_values: Optional[builtins.dict[str, Any]] = None,
    ) -> T:
        """
        Insert the instance, or update the row it conflicts with on
        ``conflict_target`` (the primary key by default), in one statement, and
        fill the instance with the stored row. ``update_fields`` (by default
        all inserted fields but the target and the key, none with
        ``update_values``), ``update_values`` and the fields with ``on_update``
        are updated.

        PostgreSQL and SQLite return the stored row from the insert. MySQL has
        no RETURNING and conflicts on any unique key: the row is read back by
        the ``conflict_target`` values.

        Sends pre_save and post_save signals, whether the row was inserted or
        updated.

        :param conflict_target: names of the fields of the conflicting unique key
        :type conflict_target: Optional[list[str]]
        :param update_fields: names of the fields updated on conflict
        :type update_fields: Optional[list[str]]
        :param update_values: values or expressions set on conflict, by field
        :type update_values: Optional[dict[str, Any]]
        :raises QueryDefinitionError: if a field of the target has no value or
            ``update_values`` are invalid (see ``_conflict_updates``)
        :raises NoMatch: if on MySQL no row matches the target values after the
            write (a conflict on another unique key, or values the database
            stores rounded)
        :return: the stored row
        :rtype: Model
        """
        self.verify_writable()
        on_update, values = self._conflict_updates(
            update_fields=update_fields, update_values=update_values
        )
        await self._emit_signal("pre_save", instance=self)
        self_fields = self._prepare_insert_row()
        config = self.ormar_config
        target_fields = conflict_target or list(config.pk.fields)
        unknown = [name for name in target_fields if name not in config.model_fields]
        if unknown:
            raise QueryDefinitionError(
                f"conflict_target names fields the model does not have: {unknown}"
            )
        target = {
            column: self_fields.get(column)
            for field_name in target_fields
            for column in self.get_column_aliases(field_name=field_name)
        }
        missing = [column for column, value in target.items() if value is None]
        if missing:
            raise QueryDefinitionError(
                f"on_conflict='update' needs a value for every field of the "
                f"conflict target, missing: {missing}"
            )
        rules = config.database.rules
        template = insert_template(
            model_cls=type(self),
            values=self_fields,
            on_conflict="update",
            conflict_target=conflict_target,
            update_fields=update_fields,
            on_update=tuple(sorted(on_update)),
            update_values=values,
            returning=(
                tuple(column.name for column in config.table.columns)
                if rules.conflict_returning
                else ()
            ),
        )
        params = {
            **template.params,
            **{
                f"ormar_on_update_{column}": value
                for column, value in on_update.items()
            },
            **update_values_params(update_values=values),
        }
        # each branch runs on its own databases only
        if rules.conflict_returning:  # pragma: no cover
            row = await self._execute_query(
                expr=template.statement, is_select=True, params=params
            )
        else:  # pragma: no cover
            await self._execute_query(expr=template.statement, params=params)
            table = config.table
            row = await self._execute_query(
                expr=sqlalchemy.select(table).where(
                    *(table.c[column] == value for column, value in target.items())
                ),
                is_select=True,
            )
            if row is None:
                raise NoMatch(
                    f"The row was written, but no row matches the conflict target "
                    f"{target} when read back: the conflict was on another unique "
                    f"key, or the database stored different values (rounded "
                    f"floats or datetimes)"
                )
        self.update_from_dict(self.translate_row_to_fields(row=dict(row)))
        self.set_save_status(True)
        self._reset_change_tracking()
        await self._emit_signal("post_save", instance=self)
        return self

    async def save_related(  # noqa: CCR001, CFQ002
        self,
        follow: bool = False,
        save_all: bool = False,
        relation_map: Optional[builtins.dict] = None,
        exclude: Union[set, builtins.dict, None] = None,
        update_count: int = 0,
        previous_model: Optional["Model"] = None,
        relation_field: Optional["ForeignKeyField"] = None,
    ) -> int:
        """
        Triggers a upsert method on all related models
        if the instances are not already saved.
        By default saves only the directly related ones.

        If follow=True is set it saves also related models of related models.

        To not get stuck in an infinite loop as related models also keep a relation
        to parent model visited models set is kept.

        That way already visited models that are nested are saved, but the save do not
        follow them inside. So Model A -> Model B -> Model A -> Model C will save second
        Model A but will never follow into Model C.
        Nested relations of those kind need to be persisted manually.

        :param relation_field: field with relation leading to this model
        :type relation_field: Optional[ForeignKeyField]
        :param previous_model: previous model from which method came
        :type previous_model: Model
        :param exclude: items to exclude during saving of relations
        :type exclude: Union[set, dict]
        :param relation_map: map of relations to follow
        :type relation_map: dict
        :param save_all: flag if all models should be saved or only not saved ones
        :type save_all: bool
        :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: number of updated/saved models
        :rtype: int
        """
        self.verify_writable()
        relation_map = (
            relation_map
            if relation_map is not None
            else cast(builtins.dict, self._default_relation_map())
        )
        if exclude and isinstance(exclude, set):
            exclude = translate_list_to_dict(exclude)
        relation_map = subtract_dict(relation_map, exclude or {})

        if relation_map:
            fields_to_visit = {
                field
                for field in self.extract_related_fields()
                if field.name in relation_map
            }
            pre_save = {
                field
                for field in fields_to_visit
                if not field.virtual and not field.is_multi
            }

            update_count = await self._update_relation_list(
                fields_list=pre_save,
                follow=follow,
                save_all=save_all,
                relation_map=relation_map,
                update_count=update_count,
            )

            update_count = await self._upsert_model(
                instance=self,
                save_all=save_all,
                previous_model=previous_model,
                relation_field=relation_field,
                update_count=update_count,
            )

            post_save = fields_to_visit - pre_save

            update_count = await self._update_relation_list(
                fields_list=post_save,
                follow=follow,
                save_all=save_all,
                relation_map=relation_map,
                update_count=update_count,
            )

        else:
            update_count = await self._upsert_model(
                instance=self,
                save_all=save_all,
                previous_model=previous_model,
                relation_field=relation_field,
                update_count=update_count,
            )

        return update_count

    async def update(
        self: T,
        _columns: Optional[list[str]] = None,
        _partial: Optional[bool] = None,
        **kwargs: Any,
    ) -> T:
        """
        Performs update of Model instance in the database.
        Fields can be updated before or you can pass them as kwargs.

        Which columns are written:

        * ``_columns`` given: only those (and ``onupdate`` fields),
        * nothing changed since the model was loaded or saved: all columns,
        * partial update (``_partial=True``, or ``partial_updates=True`` in
          ``OrmarConfig`` when ``_partial`` is not given): the kwargs, the
          fields assigned since the last load or save (also by ``pre_update``
          signal handlers), json fields mutated in place (with
          ``partial_updates=True``) and ``onupdate`` fields,
        * otherwise all columns. With the default ``partial_updates=None`` a
          ``DeprecationWarning`` is emitted when kwargs are passed and other
          columns are written too, as the default changes in a future
          release.

        Sends pre_update and post_update signals.

        Sets model save status to True.

        :param _columns: list of columns to update
        :type _columns: Optional[list[str]]
        :param _partial: write only changed fields (``True``) or all columns
            (``False``), ``None`` follows ``partial_updates`` of the config
        :type _partial: Optional[bool]
        :raises ModelPersistenceError: If the pk column is not set

        :param kwargs: list of fields to update as field=value pairs
        :type kwargs: Any
        :return: updated Model
        :rtype: Model
        """
        self.verify_writable()
        explicit_fields = self.__setattr_fields__ | kwargs.keys()
        auto_onupdate = self._onupdate_fields - explicit_fields
        values = self.populate_onupdate_value(
            dict(kwargs), explicit_fields=explicit_fields
        )
        if values:
            self.update_from_dict(values)

        if self.persisted_key is None:
            raise ModelPersistenceError(
                "You cannot update not saved model! Use save or upsert method."
            )

        await self._emit_signal("pre_update", instance=self, passed_args=kwargs)
        self_fields = self._extract_model_db_fields()
        key_fields = {
            value_key
            for field in self.ormar_config.pk.fields
            for value_key in self.value_keys(field_name=field)
        }
        key_moved = self.persisted_key != self.pk
        if not key_moved:
            for field in key_fields:
                self_fields.pop(field, None)
        self_fields = self._fields_to_update(
            self_fields=self_fields,
            columns=_columns,
            partial=_partial,
            changed=self._changed_fields() - auto_onupdate,
            passed_kwargs=bool(kwargs),
            key_fields=key_fields if key_moved else set(),
        )
        if self_fields:
            self_fields = self.translate_columns_to_aliases(self_fields)
            template = row_template(
                statement=UpdateWrite,
                model_cls=type(self),
                values=self_fields,
                pk=self.persisted_key,
            )
            await self._execute_query(expr=template.statement, params=template.params)
        self.set_save_status(True)
        self._reset_change_tracking()
        await self._emit_signal("post_update", instance=self)
        return self

    def _fields_to_update(  # noqa: CFQ002
        self,
        self_fields: builtins.dict[str, Any],
        columns: Optional[list[str]],
        partial: Optional[bool],
        changed: set[str],
        passed_kwargs: bool,
        key_fields: set[str],
    ) -> builtins.dict[str, Any]:
        """
        Selects the column values ``update()`` writes, see its docstring.

        :param self_fields: values of all columns of the model by field name
        :type self_fields: dict[str, Any]
        :param columns: ``_columns`` passed to ``update()``
        :type columns: Optional[list[str]]
        :param partial: ``_partial`` passed to ``update()``
        :type partial: Optional[bool]
        :param changed: fields changed since the last load or save
        :type changed: set[str]
        :param passed_kwargs: if ``update()`` received field values
        :type passed_kwargs: bool
        :param key_fields: primary key fields to write as the key moved
        :type key_fields: set[str]
        :return: values of the columns to write
        :rtype: dict[str, Any]
        """
        if columns:
            return self._select_update_columns(
                self_fields=self_fields, field_names=set(columns) | key_fields
            )
        if partial is None:
            partial = self.ormar_config.partial_updates
        if not changed or partial is False:
            return self_fields
        selected = self._select_update_columns(
            self_fields=self_fields, field_names=changed | key_fields
        )
        if partial:
            return selected
        if passed_kwargs and selected.keys() != self_fields.keys():
            warnings.warn(
                f"{self.get_name(lower=False)}.update(**kwargs) writes all columns "
                "of the row, not only the passed and changed fields, which reverts "
                "changes made in the database since the model was loaded. Set "
                "`partial_updates=True` in `OrmarConfig` to write only the changed "
                "fields (the default in a future release), `partial_updates=False` "
                "to keep writing all columns, or pass `_columns`.",
                DeprecationWarning,
                stacklevel=3,
            )
        return self_fields

    def _select_update_columns(
        self, self_fields: builtins.dict[str, Any], field_names: set[str]
    ) -> builtins.dict[str, Any]:
        """
        Keeps the values of the given fields (by field or column name; a foreign
        key stored in several columns keeps all of them, a column it shares
        with other fields under the key that column is kept under, see
        ``value_keys``) and of ``onupdate`` fields.

        :param self_fields: values of the model columns by field name
        :type self_fields: dict[str, Any]
        :param field_names: names of fields to keep
        :type field_names: set[str]
        :return: values of the selected columns
        :rtype: dict[str, Any]
        """
        model_fields = self.ormar_config.model_fields
        selected = set(field_names) | self._onupdate_fields
        for name in field_names:
            selected.update(self.get_column_aliases(field_name=name))
            field = model_fields.get(name)
            if field is not None and field.kind.holds_columns:
                selected.update(self.value_keys(field_name=name))
        return {k: v for k, v in self_fields.items() if k in selected}

    async def delete(self) -> int:
        """
        Removes the Model instance from the database.

        Sends pre_delete and post_delete signals.

        Sets model save status to False.

        Note it does not delete the Model itself (python object).
        So you can delete and later save (since pk is deleted no conflict will arise)
        or update and the Model will be saved in database again.

        :return: number of deleted rows (for some backends)
        :rtype: int
        """
        self.verify_writable()
        await self._emit_signal("pre_delete", instance=self)
        template = row_template(
            statement=DeleteWrite, model_cls=type(self), pk=self.persisted_key
        )
        result = await self._execute_query(
            expr=template.statement, params=template.params
        )
        self.set_save_status(False)
        self.set_persisted(persisted=False)
        await self._emit_signal("post_delete", instance=self)
        return result

    async def _load_by_set_fields(self) -> dict[str, Any]:
        """
        Load the row of a key-only model referenced by a unique non-pk field
        (``ForeignKey(to_field=...)``): it has no primary key, so the row is
        looked up by its set own fields.

        :raises NoMatch: if no row matches
        :return: values of the row by field name
        :rtype: dict[str, Any]
        """
        own_fields = self.extract_db_own_fields()
        lookup = {
            name: value
            for name, value in self.__dict__.items()
            if name in own_fields and value is not None
        }
        found = await type(self).objects.get(**lookup)
        return {name: found.__dict__[name] for name in own_fields}

    async def load(self: T) -> T:
        """
        Allow to refresh existing Models fields from database.
        Be careful as the related models can be overwritten by pk_only models in load.
        Does NOT refresh the related models fields if they were loaded before.

        :raises NoMatch: If given pk is not found in database.

        :return: reloaded Model
        :rtype: Model
        """
        if self.persisted_key is None and self.__pk_only__:
            kwargs = await self._load_by_set_fields()
        elif self.persisted_key is None:
            raise NoMatch(
                f"{self.get_name(lower=False)} has no primary key, it cannot be "
                "loaded from the database"
            )
        else:
            template = row_template(
                statement=RowSelectWrite, model_cls=type(self), pk=self.persisted_key
            )
            row = await self._execute_query(
                expr=template.statement, is_select=True, params=template.params
            )
            if not row:  # pragma nocover
                raise NoMatch(
                    "Instance was deleted from database and cannot be refreshed"
                )
            kwargs = self.translate_row_to_fields(row=dict(row))
        self.update_from_dict(kwargs)
        self.set_save_status(True)
        self._reset_change_tracking()
        return self

    async def load_all(
        self: T,
        follow: bool = False,
        exclude: Union[list, str, set, dict, None] = None,
        order_by: Union[list, str, None] = None,
        max_depth: Optional[int] = None,
        follow_reverse: Union[bool, int] = 0,
    ) -> T:
        """
        Allow to refresh existing Models fields from database.
        Performs refresh of the related models fields.

        By default, loads only self and the directly related ones.

        If follow=True is set it loads also related models of related models.

        To not get stuck in an infinite loop as related models also keep a relation
        to parent model visited models set is kept.

        That way already visited models that are nested are loaded, but the load do not
        follow them inside. So Model A -> Model B -> Model C -> Model A -> Model X
        will load second Model A but will never follow into Model X.
        Nested relations of those kind need to be loaded manually.

        :param max_depth: number of relations to follow at most with
            follow=True, forward foreign keys ``DEFAULT_FOLLOW_DEPTH`` (5) deep by
            default (every relation without limit in the deprecated ``map``
            traversal)
        :type max_depth: Optional[int]
        :param follow_reverse: number of first levels where follow=True also
            follows reverse and many to many relations, ``True`` = 1
        :type follow_reverse: Union[bool, int]
        :param order_by: columns by which models should be sorted
        :type order_by: Union[list, str]
        :raises NoMatch: If given pk is not found in database.

        :param exclude: related models to exclude
        :type exclude: Union[list, str, set, 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
        :return: reloaded Model
        :rtype: Model
        """
        relations = list(self.extract_related_names())
        if follow:
            relations = self._follow_relation_paths(
                max_depth=max_depth, follow_reverse=follow_reverse
            )
        queryset = self.__class__.objects
        if exclude:
            queryset = queryset.exclude_fields(exclude)
        if order_by:
            queryset = queryset.order_by(order_by)
        instance = await queryset.select_related(relations).get(pk=self.persisted_key)
        self._orm.clear()
        self.update_from_dict(instance.model_dump())
        self._reset_change_tracking()
        return self

delete() async

Removes the Model instance from the database.

Sends pre_delete and post_delete signals.

Sets model save status to False.

Note it does not delete the Model itself (python object). So you can delete and later save (since pk is deleted no conflict will arise) or update and the Model will be saved in database again.

Returns:

Type Description
int

number of deleted rows (for some backends)

Source code in ormar/models/model.py
Python
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
async def delete(self) -> int:
    """
    Removes the Model instance from the database.

    Sends pre_delete and post_delete signals.

    Sets model save status to False.

    Note it does not delete the Model itself (python object).
    So you can delete and later save (since pk is deleted no conflict will arise)
    or update and the Model will be saved in database again.

    :return: number of deleted rows (for some backends)
    :rtype: int
    """
    self.verify_writable()
    await self._emit_signal("pre_delete", instance=self)
    template = row_template(
        statement=DeleteWrite, model_cls=type(self), pk=self.persisted_key
    )
    result = await self._execute_query(
        expr=template.statement, params=template.params
    )
    self.set_save_status(False)
    self.set_persisted(persisted=False)
    await self._emit_signal("post_delete", instance=self)
    return result

load() async

Allow to refresh existing Models fields from database. Be careful as the related models can be overwritten by pk_only models in load. Does NOT refresh the related models fields if they were loaded before.

Returns:

Type Description
Model

reloaded Model

Raises:

Type Description
NoMatch

If given pk is not found in database.

Source code in ormar/models/model.py
Python
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
async def load(self: T) -> T:
    """
    Allow to refresh existing Models fields from database.
    Be careful as the related models can be overwritten by pk_only models in load.
    Does NOT refresh the related models fields if they were loaded before.

    :raises NoMatch: If given pk is not found in database.

    :return: reloaded Model
    :rtype: Model
    """
    if self.persisted_key is None and self.__pk_only__:
        kwargs = await self._load_by_set_fields()
    elif self.persisted_key is None:
        raise NoMatch(
            f"{self.get_name(lower=False)} has no primary key, it cannot be "
            "loaded from the database"
        )
    else:
        template = row_template(
            statement=RowSelectWrite, model_cls=type(self), pk=self.persisted_key
        )
        row = await self._execute_query(
            expr=template.statement, is_select=True, params=template.params
        )
        if not row:  # pragma nocover
            raise NoMatch(
                "Instance was deleted from database and cannot be refreshed"
            )
        kwargs = self.translate_row_to_fields(row=dict(row))
    self.update_from_dict(kwargs)
    self.set_save_status(True)
    self._reset_change_tracking()
    return self

load_all(follow=False, exclude=None, order_by=None, max_depth=None, follow_reverse=0) async

Allow to refresh existing Models fields from database. Performs refresh of the related models fields.

By default, loads only self and the directly related ones.

If follow=True is set it loads also related models of related models.

To not get stuck in an infinite loop as related models also keep a relation to parent model visited models set is kept.

That way already visited models that are nested are loaded, but the load do not follow them inside. So Model A -> Model B -> Model C -> Model A -> Model X will load second Model A but will never follow into Model X. Nested relations of those kind need to be loaded manually.

Parameters:

Name Type Description Default
max_depth Optional[int]

number of relations to follow at most with follow=True, forward foreign keys DEFAULT_FOLLOW_DEPTH (5) deep by default (every relation without limit in the deprecated map traversal)

None
follow_reverse Union[bool, int]

number of first levels where follow=True also follows reverse and many to many relations, True = 1

0
order_by Union[list, str, None]

columns by which models should be sorted

None
exclude Union[list, str, set, dict, None]

related models to exclude

None
follow bool

flag to trigger deep save - by default only directly related models are saved with follow=True also related models of related models are saved

False

Returns:

Type Description
Model

reloaded Model

Raises:

Type Description
NoMatch

If given pk is not found in database.

Source code in ormar/models/model.py
Python
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
async def load_all(
    self: T,
    follow: bool = False,
    exclude: Union[list, str, set, dict, None] = None,
    order_by: Union[list, str, None] = None,
    max_depth: Optional[int] = None,
    follow_reverse: Union[bool, int] = 0,
) -> T:
    """
    Allow to refresh existing Models fields from database.
    Performs refresh of the related models fields.

    By default, loads only self and the directly related ones.

    If follow=True is set it loads also related models of related models.

    To not get stuck in an infinite loop as related models also keep a relation
    to parent model visited models set is kept.

    That way already visited models that are nested are loaded, but the load do not
    follow them inside. So Model A -> Model B -> Model C -> Model A -> Model X
    will load second Model A but will never follow into Model X.
    Nested relations of those kind need to be loaded manually.

    :param max_depth: number of relations to follow at most with
        follow=True, forward foreign keys ``DEFAULT_FOLLOW_DEPTH`` (5) deep by
        default (every relation without limit in the deprecated ``map``
        traversal)
    :type max_depth: Optional[int]
    :param follow_reverse: number of first levels where follow=True also
        follows reverse and many to many relations, ``True`` = 1
    :type follow_reverse: Union[bool, int]
    :param order_by: columns by which models should be sorted
    :type order_by: Union[list, str]
    :raises NoMatch: If given pk is not found in database.

    :param exclude: related models to exclude
    :type exclude: Union[list, str, set, 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
    :return: reloaded Model
    :rtype: Model
    """
    relations = list(self.extract_related_names())
    if follow:
        relations = self._follow_relation_paths(
            max_depth=max_depth, follow_reverse=follow_reverse
        )
    queryset = self.__class__.objects
    if exclude:
        queryset = queryset.exclude_fields(exclude)
    if order_by:
        queryset = queryset.order_by(order_by)
    instance = await queryset.select_related(relations).get(pk=self.persisted_key)
    self._orm.clear()
    self.update_from_dict(instance.model_dump())
    self._reset_change_tracking()
    return self

save() async

Performs a save of given Model instance. If primary key is already saved, db backend will throw integrity error.

Related models are saved by pk number, reverse relation and many to many fields are not saved - use corresponding relations methods.

If there are fields with server_default set and those fields are not already filled save will trigger also a second query to refreshed the fields populated server side.

Does not recognize if model was previously saved. If you want to perform update or insert depending on the pk fields presence use upsert.

Sends pre_save and post_save signals.

Sets model save status to True.

Returns:

Type Description
Model

saved Model

Source code in ormar/models/model.py
Python
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
async def save(self: T) -> T:
    """
    Performs a save of given Model instance.
    If primary key is already saved, db backend will throw integrity error.

    Related models are saved by pk number, reverse relation and many to many fields
    are not saved - use corresponding relations methods.

    If there are fields with server_default set and those fields
    are not already filled save will trigger also a second query
    to refreshed the fields populated server side.

    Does not recognize if model was previously saved.
    If you want to perform update or insert depending on the pk
    fields presence use upsert.

    Sends pre_save and post_save signals.

    Sets model save status to True.

    :return: saved Model
    :rtype: Model
    """
    return cast(T, await self._save())

Triggers a upsert method on all related models if the instances are not already saved. By default saves only the directly related ones.

If follow=True is set it saves also related models of related models.

To not get stuck in an infinite loop as related models also keep a relation to parent model visited models set is kept.

That way already visited models that are nested are saved, but the save do not follow them inside. So Model A -> Model B -> Model A -> Model C will save second Model A but will never follow into Model C. Nested relations of those kind need to be persisted manually.

Parameters:

Name Type Description Default
relation_field Optional[ForeignKeyField]

field with relation leading to this model

None
previous_model Optional[Model]

previous model from which method came

None
exclude Union[set, dict, None]

items to exclude during saving of relations

None
relation_map Optional[dict]

map of relations to follow

None
save_all bool

flag if all models should be saved or only not saved ones

False
follow bool

flag to trigger deep save - by default only directly related models are saved with follow=True also related models of related models are saved

False
update_count int

internal parameter for recursive calls - number of updated instances

0

Returns:

Type Description
int

number of updated/saved models

Source code in ormar/models/model.py
Python
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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
async def save_related(  # noqa: CCR001, CFQ002
    self,
    follow: bool = False,
    save_all: bool = False,
    relation_map: Optional[builtins.dict] = None,
    exclude: Union[set, builtins.dict, None] = None,
    update_count: int = 0,
    previous_model: Optional["Model"] = None,
    relation_field: Optional["ForeignKeyField"] = None,
) -> int:
    """
    Triggers a upsert method on all related models
    if the instances are not already saved.
    By default saves only the directly related ones.

    If follow=True is set it saves also related models of related models.

    To not get stuck in an infinite loop as related models also keep a relation
    to parent model visited models set is kept.

    That way already visited models that are nested are saved, but the save do not
    follow them inside. So Model A -> Model B -> Model A -> Model C will save second
    Model A but will never follow into Model C.
    Nested relations of those kind need to be persisted manually.

    :param relation_field: field with relation leading to this model
    :type relation_field: Optional[ForeignKeyField]
    :param previous_model: previous model from which method came
    :type previous_model: Model
    :param exclude: items to exclude during saving of relations
    :type exclude: Union[set, dict]
    :param relation_map: map of relations to follow
    :type relation_map: dict
    :param save_all: flag if all models should be saved or only not saved ones
    :type save_all: bool
    :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: number of updated/saved models
    :rtype: int
    """
    self.verify_writable()
    relation_map = (
        relation_map
        if relation_map is not None
        else cast(builtins.dict, self._default_relation_map())
    )
    if exclude and isinstance(exclude, set):
        exclude = translate_list_to_dict(exclude)
    relation_map = subtract_dict(relation_map, exclude or {})

    if relation_map:
        fields_to_visit = {
            field
            for field in self.extract_related_fields()
            if field.name in relation_map
        }
        pre_save = {
            field
            for field in fields_to_visit
            if not field.virtual and not field.is_multi
        }

        update_count = await self._update_relation_list(
            fields_list=pre_save,
            follow=follow,
            save_all=save_all,
            relation_map=relation_map,
            update_count=update_count,
        )

        update_count = await self._upsert_model(
            instance=self,
            save_all=save_all,
            previous_model=previous_model,
            relation_field=relation_field,
            update_count=update_count,
        )

        post_save = fields_to_visit - pre_save

        update_count = await self._update_relation_list(
            fields_list=post_save,
            follow=follow,
            save_all=save_all,
            relation_map=relation_map,
            update_count=update_count,
        )

    else:
        update_count = await self._upsert_model(
            instance=self,
            save_all=save_all,
            previous_model=previous_model,
            relation_field=relation_field,
            update_count=update_count,
        )

    return update_count

update(_columns=None, _partial=None, **kwargs) async

Performs update of Model instance in the database. Fields can be updated before or you can pass them as kwargs.

Which columns are written:

  • _columns given: only those (and onupdate fields),
  • nothing changed since the model was loaded or saved: all columns,
  • partial update (_partial=True, or partial_updates=True in OrmarConfig when _partial is not given): the kwargs, the fields assigned since the last load or save (also by pre_update signal handlers), json fields mutated in place (with partial_updates=True) and onupdate fields,
  • otherwise all columns. With the default partial_updates=None a DeprecationWarning is emitted when kwargs are passed and other columns are written too, as the default changes in a future release.

Sends pre_update and post_update signals.

Sets model save status to True.

Parameters:

Name Type Description Default
_columns Optional[list[str]]

list of columns to update

None
_partial Optional[bool]

write only changed fields (True) or all columns (False), None follows partial_updates of the config

None
kwargs Any

list of fields to update as field=value pairs

{}

Returns:

Type Description
Model

updated Model

Raises:

Type Description
ModelPersistenceError

If the pk column is not set

Source code in ormar/models/model.py
Python
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
async def update(
    self: T,
    _columns: Optional[list[str]] = None,
    _partial: Optional[bool] = None,
    **kwargs: Any,
) -> T:
    """
    Performs update of Model instance in the database.
    Fields can be updated before or you can pass them as kwargs.

    Which columns are written:

    * ``_columns`` given: only those (and ``onupdate`` fields),
    * nothing changed since the model was loaded or saved: all columns,
    * partial update (``_partial=True``, or ``partial_updates=True`` in
      ``OrmarConfig`` when ``_partial`` is not given): the kwargs, the
      fields assigned since the last load or save (also by ``pre_update``
      signal handlers), json fields mutated in place (with
      ``partial_updates=True``) and ``onupdate`` fields,
    * otherwise all columns. With the default ``partial_updates=None`` a
      ``DeprecationWarning`` is emitted when kwargs are passed and other
      columns are written too, as the default changes in a future
      release.

    Sends pre_update and post_update signals.

    Sets model save status to True.

    :param _columns: list of columns to update
    :type _columns: Optional[list[str]]
    :param _partial: write only changed fields (``True``) or all columns
        (``False``), ``None`` follows ``partial_updates`` of the config
    :type _partial: Optional[bool]
    :raises ModelPersistenceError: If the pk column is not set

    :param kwargs: list of fields to update as field=value pairs
    :type kwargs: Any
    :return: updated Model
    :rtype: Model
    """
    self.verify_writable()
    explicit_fields = self.__setattr_fields__ | kwargs.keys()
    auto_onupdate = self._onupdate_fields - explicit_fields
    values = self.populate_onupdate_value(
        dict(kwargs), explicit_fields=explicit_fields
    )
    if values:
        self.update_from_dict(values)

    if self.persisted_key is None:
        raise ModelPersistenceError(
            "You cannot update not saved model! Use save or upsert method."
        )

    await self._emit_signal("pre_update", instance=self, passed_args=kwargs)
    self_fields = self._extract_model_db_fields()
    key_fields = {
        value_key
        for field in self.ormar_config.pk.fields
        for value_key in self.value_keys(field_name=field)
    }
    key_moved = self.persisted_key != self.pk
    if not key_moved:
        for field in key_fields:
            self_fields.pop(field, None)
    self_fields = self._fields_to_update(
        self_fields=self_fields,
        columns=_columns,
        partial=_partial,
        changed=self._changed_fields() - auto_onupdate,
        passed_kwargs=bool(kwargs),
        key_fields=key_fields if key_moved else set(),
    )
    if self_fields:
        self_fields = self.translate_columns_to_aliases(self_fields)
        template = row_template(
            statement=UpdateWrite,
            model_cls=type(self),
            values=self_fields,
            pk=self.persisted_key,
        )
        await self._execute_query(expr=template.statement, params=template.params)
    self.set_save_status(True)
    self._reset_change_tracking()
    await self._emit_signal("post_update", instance=self)
    return self

upsert(**kwargs) async

Performs either a save or an update:

  • a model loaded from or already saved to the database is updated,
  • a model without a primary key is inserted,
  • a model never saved but with its key set (uuid default, natural or composite key) is looked up first and updated if the row exists, inserted otherwise.

For save kwargs are ignored, used only in update if provided. __force_save__ is accepted for backwards compatibility and ignored.

Parameters:

Name Type Description Default
kwargs Any

list of fields to update

{}

Returns:

Type Description
Model

saved Model

Source code in ormar/models/model.py
Python
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
async def upsert(self: T, **kwargs: Any) -> T:
    """
    Performs either a save or an update:

    * a model loaded from or already saved to the database is updated,
    * a model without a primary key is inserted,
    * a model never saved but with its key set (uuid default, natural or
      composite key) is looked up first and updated if the row exists,
      inserted otherwise.

    For save kwargs are ignored, used only in update if provided.
    ``__force_save__`` is accepted for backwards compatibility and ignored.

    :param kwargs: list of fields to update
    :type kwargs: Any
    :return: saved Model
    :rtype: Model
    """
    self.verify_writable()
    kwargs.pop("__force_save__", None)
    if self.persisted:
        return await self.update(**kwargs)
    if self.pk is None:
        return await self.save()
    template = row_template(
        statement=RowSelectWrite, model_cls=type(self), pk=self.pk
    )
    row = await self._execute_query(
        expr=template.statement, is_select=True, params=template.params
    )
    if not row:
        return await self.save()
    return await self.update(_partial=False, **kwargs)

ModelDefinitionError

Bases: AsyncOrmException

Raised for errors related to the model definition itself:

  • defining a Field without required parameters
  • defining a model with more than one primary_key
  • defining a model without primary_key
Source code in ormar/exceptions.py
Python
14
15
16
17
18
19
20
21
22
23
class ModelDefinitionError(AsyncOrmException):
    """
    Raised for errors related to the model definition itself:

    * defining a Field without required parameters
    * defining a model with more than one primary_key
    * defining a model without primary_key
    """

    pass

MultipleMatches

Bases: AsyncOrmException

Raised for database queries that should return one row (i.e. get, first etc.) but has multiple matching results in response.

Source code in ormar/exceptions.py
Python
51
52
53
54
55
56
57
class MultipleMatches(AsyncOrmException):
    """
    Raised for database queries that should return one row (i.e. get, first etc.)
    but has multiple matching results in response.
    """

    pass

NoMatch

Bases: AsyncOrmException

Raised for database queries that has no matching result (empty result).

Source code in ormar/exceptions.py
Python
43
44
45
46
47
48
class NoMatch(AsyncOrmException):
    """
    Raised for database queries that has no matching result (empty result).
    """

    pass

NullsOrdering

Bases: str, Enum

Nulls placement options for the .order_by() queries.

Source code in ormar/queryset/clause.py
Python
27
28
29
30
31
class NullsOrdering(str, Enum):
    """Nulls placement options for the `.order_by()` queries."""

    FIRST = "first"
    LAST = "last"

OrderAction

Bases: QueryAction

Represents a single ORDER BY directive on a queryset.

Created when order_by(...) or Field.asc() / Field.desc() is used, and internally to apply the default primary-key ordering.

Source code in ormar/queryset/actions/order_action.py
Python
 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
class OrderAction(QueryAction):
    """
    Represents a single ORDER BY directive on a queryset.

    Created when ``order_by(...)`` or ``Field.asc()`` / ``Field.desc()`` is
    used, and internally to apply the default primary-key ordering.
    """

    def __init__(
        self,
        order_str: str,
        model_cls: type["Model"],
        alias: Optional[str] = None,
        nulls_ordering: Optional[str] = None,
    ) -> None:
        self.direction: str = ""
        super().__init__(query_str=order_str, model_cls=model_cls)
        self.is_source_model_order = False
        if alias:
            self.table_prefix = alias
        if self.source_model == self.target_model and "__" not in self.related_str:
            self.is_source_model_order = True
        self.nulls_ordering = nulls_ordering

    @property
    def field_alias(self) -> str:
        return self.target_model.get_column_alias(self.field_name)

    @property
    def field_aliases(self) -> tuple[str, ...]:
        """
        :return: columns the field is ordered by: its column, or every column
            of a foreign key stored in several columns
        :rtype: tuple[str, ...]
        """
        return self.target_model.get_column_aliases(field_name=self.field_name)

    def get_field_name_text(self) -> str:
        """
        Escapes characters if it's required.
        Substitutes values of the models if value is a ormar Model with its pk value.
        Compiles the clause.

        :return: complied and escaped clause
        :rtype: sqlalchemy.sql.elements.TextClause
        """
        prefix = f"{self.table_prefix}_" if self.table_prefix else ""
        return f"{prefix}{self.table.name}.{self.field_alias}"

    def get_min_or_max(self) -> sqlalchemy.sql.expression.TextClause:
        """
        Used in limit sub queries where you need to use aggregated functions
        in order to order by columns not included in group by. For postgres bool
        field it's using bool_or function as aggregates does not work with this type
        of columns.

        :return: min or max function to order
        :rtype: sqlalchemy.sql.elements.TextClause
        """
        prefix = f"{self.table_prefix}_" if self.table_prefix else ""
        config = self.target_model.ormar_config
        function = config.database.rules.ordering_aggregate(
            field_type=config.model_fields[self.field_name].__type__,
            descending=bool(self.direction),
        )
        suffix = " desc" if self.direction else ""
        return text(
            ", ".join(
                f"{function}({prefix}{self.table.name}.{alias}){suffix}"
                for alias in self.field_aliases
            )
        )

    def get_text_clause(self) -> sqlalchemy.sql.expression.TextClause:
        """
        Escapes characters if it's required.
        Substitutes values of the models if value is a ormar Model with its pk value.
        Compiles the clause.

        :return: complied and escaped clause
        :rtype: sqlalchemy.sql.elements.TextClause
        """
        dialect = self.target_model.ormar_config.database.dialect
        quoter = dialect.identifier_preparer.quote
        prefix = f"{self.table_prefix}_" if self.table_prefix else ""
        table_name = quoter(f"{prefix}{self.table.name}")
        return order_text_clause(
            ", ".join(
                self._build_order_expression(f"{table_name}.{quoter(alias)}")
                for alias in self.field_aliases
            )
        )

    def _build_order_expression(self, full_column: str) -> str:
        """
        Builds the final ORDER BY expression for a fully-qualified column,
        optionally including a `NULLS FIRST`/`NULLS LAST` annotation (emulated
        by the dialect rules where the syntax is missing).

        :param full_column: fully-qualified, quoted column reference
        :type full_column: str
        :return: ORDER BY expression as raw SQL text
        :rtype: str
        """
        direction = f" {self.direction}" if self.direction else ""
        base = f"{full_column}{direction}"
        if self.nulls_ordering is None:
            return base
        return self.target_model.ormar_config.database.rules.nulls_order(
            full_column=full_column, ordered=base, nulls_ordering=self.nulls_ordering
        )

    def _split_value_into_parts(self, order_str: str) -> None:
        if order_str.startswith("-"):
            self.direction = "desc"
            order_str = order_str[1:]
        parts = order_str.split("__")
        self.field_name = parts[-1]
        self.related_parts = parts[:-1]

    @classmethod
    def from_model_defaults(cls, model_cls: type["Model"]) -> list["OrderAction"]:
        """
        Builds the default list of ``OrderAction`` instances from a model's
        ``OrmarConfig.orders_by`` (which always contains at least the primary
        key, populated by the metaclass).

        :param model_cls: model class whose defaults should be used
        :type model_cls: type["Model"]
        :return: list of default OrderAction instances for the model
        :rtype: list[OrderAction]
        """
        return [
            action
            for name in model_cls.ormar_config.orders_by
            for action in order_actions_for(order_str=str(name), model_cls=model_cls)
        ]

    def flipped(self) -> "OrderAction":
        """
        Returns a shallow copy of this order action with the sort direction
        and any `NULLS FIRST`/`NULLS LAST` annotation inverted.

        Used by reverse slicing to turn an ASC/DESC ordering into its mirror
        image so that ``LIMIT N`` fetches rows from the tail of the original
        ordering. Callers are responsible for reversing the result list in
        memory afterwards so the caller-visible ordering is preserved.

        :return: new OrderAction with flipped direction and nulls ordering
        :rtype: OrderAction
        """
        flipped = copy.copy(self)
        flipped.direction = "" if self.direction == "desc" else "desc"
        if self.nulls_ordering == "first":
            flipped.nulls_ordering = "last"
        elif self.nulls_ordering == "last":
            flipped.nulls_ordering = "first"
        return flipped

    def check_if_filter_apply(self, target_model: type["Model"], alias: str) -> bool:
        """
        Checks filter conditions to find if they apply to current join.

        :param target_model: model which is now processed
        :type target_model: type["Model"]
        :param alias: prefix of the relation
        :type alias: str
        :return: result of the check
        :rtype: bool
        """
        return target_model == self.target_model and alias == self.table_prefix

field_aliases property

Returns:

Type Description
tuple[str, ...]

columns the field is ordered by: its column, or every column of a foreign key stored in several columns

check_if_filter_apply(target_model, alias)

Checks filter conditions to find if they apply to current join.

Parameters:

Name Type Description Default
target_model type[Model]

model which is now processed

required
alias str

prefix of the relation

required

Returns:

Type Description
bool

result of the check

Source code in ormar/queryset/actions/order_action.py
Python
192
193
194
195
196
197
198
199
200
201
202
203
def check_if_filter_apply(self, target_model: type["Model"], alias: str) -> bool:
    """
    Checks filter conditions to find if they apply to current join.

    :param target_model: model which is now processed
    :type target_model: type["Model"]
    :param alias: prefix of the relation
    :type alias: str
    :return: result of the check
    :rtype: bool
    """
    return target_model == self.target_model and alias == self.table_prefix

flipped()

Returns a shallow copy of this order action with the sort direction and any NULLS FIRST/NULLS LAST annotation inverted.

Used by reverse slicing to turn an ASC/DESC ordering into its mirror image so that LIMIT N fetches rows from the tail of the original ordering. Callers are responsible for reversing the result list in memory afterwards so the caller-visible ordering is preserved.

Returns:

Type Description
OrderAction

new OrderAction with flipped direction and nulls ordering

Source code in ormar/queryset/actions/order_action.py
Python
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
def flipped(self) -> "OrderAction":
    """
    Returns a shallow copy of this order action with the sort direction
    and any `NULLS FIRST`/`NULLS LAST` annotation inverted.

    Used by reverse slicing to turn an ASC/DESC ordering into its mirror
    image so that ``LIMIT N`` fetches rows from the tail of the original
    ordering. Callers are responsible for reversing the result list in
    memory afterwards so the caller-visible ordering is preserved.

    :return: new OrderAction with flipped direction and nulls ordering
    :rtype: OrderAction
    """
    flipped = copy.copy(self)
    flipped.direction = "" if self.direction == "desc" else "desc"
    if self.nulls_ordering == "first":
        flipped.nulls_ordering = "last"
    elif self.nulls_ordering == "last":
        flipped.nulls_ordering = "first"
    return flipped

from_model_defaults(model_cls) classmethod

Builds the default list of OrderAction instances from a model's OrmarConfig.orders_by (which always contains at least the primary key, populated by the metaclass).

Parameters:

Name Type Description Default
model_cls type[Model]

model class whose defaults should be used

required

Returns:

Type Description
list[OrderAction]

list of default OrderAction instances for the model

Source code in ormar/queryset/actions/order_action.py
Python
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
@classmethod
def from_model_defaults(cls, model_cls: type["Model"]) -> list["OrderAction"]:
    """
    Builds the default list of ``OrderAction`` instances from a model's
    ``OrmarConfig.orders_by`` (which always contains at least the primary
    key, populated by the metaclass).

    :param model_cls: model class whose defaults should be used
    :type model_cls: type["Model"]
    :return: list of default OrderAction instances for the model
    :rtype: list[OrderAction]
    """
    return [
        action
        for name in model_cls.ormar_config.orders_by
        for action in order_actions_for(order_str=str(name), model_cls=model_cls)
    ]

get_field_name_text()

Escapes characters if it's required. Substitutes values of the models if value is a ormar Model with its pk value. Compiles the clause.

Returns:

Type Description
sqlalchemy.sql.elements.TextClause

complied and escaped clause

Source code in ormar/queryset/actions/order_action.py
Python
70
71
72
73
74
75
76
77
78
79
80
def get_field_name_text(self) -> str:
    """
    Escapes characters if it's required.
    Substitutes values of the models if value is a ormar Model with its pk value.
    Compiles the clause.

    :return: complied and escaped clause
    :rtype: sqlalchemy.sql.elements.TextClause
    """
    prefix = f"{self.table_prefix}_" if self.table_prefix else ""
    return f"{prefix}{self.table.name}.{self.field_alias}"

get_min_or_max()

Used in limit sub queries where you need to use aggregated functions in order to order by columns not included in group by. For postgres bool field it's using bool_or function as aggregates does not work with this type of columns.

Returns:

Type Description
sqlalchemy.sql.elements.TextClause

min or max function to order

Source code in ormar/queryset/actions/order_action.py
Python
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
def get_min_or_max(self) -> sqlalchemy.sql.expression.TextClause:
    """
    Used in limit sub queries where you need to use aggregated functions
    in order to order by columns not included in group by. For postgres bool
    field it's using bool_or function as aggregates does not work with this type
    of columns.

    :return: min or max function to order
    :rtype: sqlalchemy.sql.elements.TextClause
    """
    prefix = f"{self.table_prefix}_" if self.table_prefix else ""
    config = self.target_model.ormar_config
    function = config.database.rules.ordering_aggregate(
        field_type=config.model_fields[self.field_name].__type__,
        descending=bool(self.direction),
    )
    suffix = " desc" if self.direction else ""
    return text(
        ", ".join(
            f"{function}({prefix}{self.table.name}.{alias}){suffix}"
            for alias in self.field_aliases
        )
    )

get_text_clause()

Escapes characters if it's required. Substitutes values of the models if value is a ormar Model with its pk value. Compiles the clause.

Returns:

Type Description
sqlalchemy.sql.elements.TextClause

complied and escaped clause

Source code in ormar/queryset/actions/order_action.py
Python
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
def get_text_clause(self) -> sqlalchemy.sql.expression.TextClause:
    """
    Escapes characters if it's required.
    Substitutes values of the models if value is a ormar Model with its pk value.
    Compiles the clause.

    :return: complied and escaped clause
    :rtype: sqlalchemy.sql.elements.TextClause
    """
    dialect = self.target_model.ormar_config.database.dialect
    quoter = dialect.identifier_preparer.quote
    prefix = f"{self.table_prefix}_" if self.table_prefix else ""
    table_name = quoter(f"{prefix}{self.table.name}")
    return order_text_clause(
        ", ".join(
            self._build_order_expression(f"{table_name}.{quoter(alias)}")
            for alias in self.field_aliases
        )
    )

Prefetch dataclass

A relation to prefetch together with the queryset its models are loaded with.

Attributes:

Name Type Description
relation str

relation path, the same __ separated string prefetch_related accepts

queryset QuerySet[Any]

queryset of the related model; its filters, excludes, ordering and fields / exclude_fields apply to the prefetched models

Source code in ormar/queryset/prefetch.py
Python
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
@dataclass(frozen=True)
class Prefetch:
    """
    A relation to prefetch together with the queryset its models are loaded
    with.

    :ivar relation: relation path, the same ``__`` separated string
        ``prefetch_related`` accepts
    :ivar queryset: queryset of the related model; its filters, excludes,
        ordering and ``fields`` / ``exclude_fields`` apply to the prefetched
        models
    """

    relation: str
    queryset: "QuerySet[Any]"

QuerySet

Bases: Generic[T]

Main class to perform database queries, exposed on each model as objects attribute.

Source code in ormar/queryset/queryset.py
Python
 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
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
class QuerySet(Generic[T]):
    """
    Main class to perform database queries, exposed on each model as objects attribute.
    """

    def __init__(  # noqa CFQ002
        self,
        model_cls: Optional[type["T"]] = None,
        filter_clauses: Optional[list] = None,
        exclude_clauses: Optional[list] = None,
        select_related: Optional[list] = None,
        limit_count: Optional[int] = None,
        offset: Optional[int] = None,
        excludable: Optional["ExcludableItems"] = None,
        order_bys: Optional[list] = None,
        prefetch_related: Optional[list] = None,
        limit_raw_sql: bool = False,
        proxy_source_model: Optional[type["Model"]] = None,
        reverse_result: bool = False,
        prefetch_querysets: Optional[dict[str, "QuerySet"]] = None,
        row_lock: Optional[dict[str, bool]] = None,
    ) -> None:
        self.proxy_source_model = proxy_source_model
        self.model_cls = model_cls
        self.filter_clauses = [] if filter_clauses is None else filter_clauses
        self.exclude_clauses = [] if exclude_clauses is None else exclude_clauses
        self._select_related = [] if select_related is None else select_related
        self._prefetch_related = [] if prefetch_related is None else prefetch_related
        self.limit_count = limit_count
        self.query_offset = offset
        self._excludable = excludable or ormar.ExcludableItems()
        self.order_bys = order_bys or []
        self.limit_sql_raw = limit_raw_sql
        self._reverse_result = reverse_result
        self._prefetch_querysets: dict[str, "QuerySet"] = (
            {} if prefetch_querysets is None else prefetch_querysets
        )
        self.row_lock = row_lock or {}

    @property
    def model_config(self) -> "OrmarConfig":
        """
        Shortcut to model class OrmarConfig set on QuerySet model.

        :return: OrmarConfig of the model
        :rtype: model's OrmarConfig
        """
        if not self.model_cls:  # pragma nocover
            raise ValueError("Model class of QuerySet is not initialized")
        return self.model_cls.ormar_config

    @property
    def model(self) -> type["T"]:
        """
        Shortcut to model class set on QuerySet.

        :return: model class
        :rtype: type[Model]
        """
        if not self.model_cls:  # pragma nocover
            raise ValueError("Model class of QuerySet is not initialized")
        return self.model_cls

    def rebuild_self(  # noqa: CFQ002
        self,
        filter_clauses: Optional[list] = None,
        exclude_clauses: Optional[list] = None,
        select_related: Optional[list] = None,
        limit_count: Optional[int] = None,
        offset: Optional[int] = None,
        excludable: Optional["ExcludableItems"] = None,
        order_bys: Optional[list] = None,
        prefetch_related: Optional[list] = None,
        limit_raw_sql: Optional[bool] = None,
        proxy_source_model: Optional[type["Model"]] = None,
        reverse_result: Optional[bool] = None,
        prefetch_querysets: Optional[dict[str, "QuerySet"]] = None,
        row_lock: Optional[dict[str, bool]] = None,
    ) -> "QuerySet":
        """
        Method that returns new instance of queryset based on passed params,
        all not passed params are taken from current values.
        """
        overwrites = {
            "select_related": "_select_related",
            "offset": "query_offset",
            "excludable": "_excludable",
            "prefetch_related": "_prefetch_related",
            "limit_raw_sql": "limit_sql_raw",
            "reverse_result": "_reverse_result",
            "prefetch_querysets": "_prefetch_querysets",
        }
        passed_args = locals()

        def replace_if_none(arg_name: str) -> Any:
            if passed_args.get(arg_name) is None:
                return getattr(self, overwrites.get(arg_name, arg_name))
            return passed_args.get(arg_name)

        return self.__class__(
            model_cls=self.model_cls,
            filter_clauses=replace_if_none("filter_clauses"),
            exclude_clauses=replace_if_none("exclude_clauses"),
            select_related=replace_if_none("select_related"),
            limit_count=replace_if_none("limit_count"),
            offset=replace_if_none("offset"),
            excludable=replace_if_none("excludable"),
            order_bys=replace_if_none("order_bys"),
            prefetch_related=replace_if_none("prefetch_related"),
            limit_raw_sql=replace_if_none("limit_raw_sql"),
            proxy_source_model=replace_if_none("proxy_source_model"),
            reverse_result=replace_if_none("reverse_result"),
            prefetch_querysets=replace_if_none("prefetch_querysets"),
            row_lock=replace_if_none("row_lock"),
        )

    async def _prefetch_related_models(
        self, models: list["T"], rows: list
    ) -> list["T"]:
        """
        Performs prefetch query for selected models names.

        :param models: list of already parsed main Models from main query
        :type models: list[Model]
        :param rows: database rows from main query
        :type rows: list[sqlalchemy.engine.result.RowProxy]
        :return: list of models with prefetch models populated
        :rtype: list[Model]
        """
        query = PrefetchQuery(
            model_cls=self.model,
            excludable=self._excludable,
            prefetch_related=self._prefetch_related,
            select_related=self._select_related,
            orders_by=self.order_bys,
            prefetch_querysets=self._prefetch_querysets,
        )
        return await query.prefetch_related(models=models)  # type: ignore

    async def _process_query_result_rows(
        self, rows: list, plan_cache: Optional[dict] = None
    ) -> list["T"]:
        """
        Process database rows and initialize ormar Model from each of the rows.

        :param rows: list of database rows from query result
        :type rows: list[sqlalchemy.engine.result.RowProxy]
        :param plan_cache: optional row-extraction plan cache; ``iterate``
            passes a single dict shared across all chunks so amortization
            survives the per-chunk ``_process_query_result_rows`` boundary
        :type plan_cache: Optional[dict]
        :return: list of models
        :rtype: list[Model]
        """
        if plan_cache is None:
            plan_cache = {}
        if not self._select_related and self.model.trusted_row_construction():
            return await self._process_flat_rows(rows=rows, plan_cache=plan_cache)
        registry = RowRegistry()
        result_rows = []
        for i, row in enumerate(rows):
            result_rows.append(
                self.model.from_row(
                    row=row,
                    select_related=self._select_related,
                    excludable=self._excludable,
                    source_model=self.model,
                    proxy_source_model=self.proxy_source_model,
                    plan_cache=plan_cache,
                    registry=registry,
                )
            )
            if i % 100 == 99:  # pragma: no cover
                await asyncio.sleep(0)

        if result_rows:
            return self.model.merge_instances_list(  # type: ignore[return-value]
                result_rows,  # type: ignore[arg-type]
                excludable=self._excludable,
            )
        return cast(list["T"], result_rows)

    async def _process_flat_rows(self, rows: list, plan_cache: dict) -> list["T"]:
        """
        Build models of rows without joined relations of models with
        ``trusted_row_construction()`` (see ``ModelRow.from_flat_rows``).

        The rows are built in chunks of ``FLAT_ROWS_CHUNK`` with a yield to the
        event loop in between, so a large result does not block other tasks
        for the whole time it takes to build.

        :param rows: list of database rows from query result
        :type rows: list
        :param plan_cache: row-extraction plan cache
        :type plan_cache: dict
        :return: list of models
        :rtype: list[Model]
        """
        result: list["T"] = []
        registry = RowRegistry()
        for start in range(0, len(rows), FLAT_ROWS_CHUNK):
            if start:
                await asyncio.sleep(0)
            chunk = rows[start : start + FLAT_ROWS_CHUNK]
            result.extend(
                cast(
                    list["T"],
                    self.model.from_flat_rows(
                        rows=chunk,
                        excludable=self._excludable,
                        plan_cache=plan_cache,
                        registry=registry,
                    ),
                )
            )
        return result

    def _resolve_filter_groups(
        self, groups: Any
    ) -> tuple[list[FilterGroup], list[str]]:
        """
        Resolves filter groups to populate FilterAction params in group tree.

        :param groups: tuple of FilterGroups
        :type groups: Any
        :return: list of resolver groups
        :rtype: tuple[list[FilterGroup], list[str]]
        """
        filter_groups = []
        select_related = self._select_related
        if groups:
            for group in groups:
                if not isinstance(group, FilterGroup):
                    raise QueryDefinitionError(
                        "Only ormar.and_ and ormar.or_ "
                        "can be passed as filter positional"
                        " arguments,"
                        "other values need to be passed by"
                        "keyword arguments"
                    )
                _, select_related = group.resolve(
                    model_cls=self.model,
                    select_related=self._select_related,
                    filter_clauses=self.filter_clauses,
                )
                filter_groups.append(group)
        return filter_groups, select_related

    @staticmethod
    def check_single_result_rows_count(rows: Sequence[Optional["T"]]) -> None:
        """
        Verifies if the result has one and only one row.

        :param rows: one element list of Models
        :type rows: list[Model]
        """
        if not rows or rows[0] is None:
            raise NoMatch()
        if len(rows) > 1:
            raise MultipleMatches()

    @property
    def table(self) -> sqlalchemy.Table:
        """
        Shortcut to models table from OrmarConfig.

        :return: database table
        :rtype: sqlalchemy.Table
        """
        return self.model_config.table

    def build_select_expression(
        self,
        limit: Optional[int] = None,
        offset: Optional[int] = None,
        order_bys: Optional[list] = None,
        binder: Optional[SlotBinder] = None,
    ) -> sqlalchemy.sql.Select:
        """
        Constructs the actual database query used in the QuerySet.
        If any of the params is not passed the QuerySet own value is used.

        :param limit: number to limit the query
        :type limit: int
        :param offset: number to offset by
        :type offset: int
        :param order_bys: list of order-by fields names
        :type order_bys: list
        :param binder: names per-call values for statement templates, if given
        :type binder: Optional[SlotBinder]
        :return: built sqlalchemy select expression
        :rtype: sqlalchemy.sql.selectable.Select
        """
        qry = Query(
            model_cls=self.model,
            select_related=self._select_related,
            filter_clauses=self.filter_clauses,
            exclude_clauses=self.exclude_clauses,
            offset=offset or self.query_offset,
            excludable=self._excludable,
            order_bys=order_bys or self.order_bys,
            limit_raw_sql=self.limit_sql_raw,
            limit_count=limit if limit is not None else self.limit_count,
            binder=binder,
        )
        exp = qry.build_select_expression()
        if self.row_lock:
            exp = exp.with_for_update(of=self.table, **self.row_lock)
        return exp

    def build_select_template(
        self,
        variant: tuple = (),
        limit: Optional[int] = None,
        offset: Optional[int] = None,
        order_bys: Optional[list] = None,
        wrap: Optional[Callable[[sqlalchemy.sql.Select], Any]] = None,
    ) -> StatementTemplate:
        """
        Return the read statement for this queryset from the model's template
        cache (building and caching it on the first call of a cache key) together
        with the values to bind for this call::

            Author.objects.filter(name="a").build_select_template()
            # -> StatementTemplate(statement=SELECT ... WHERE name = :ormar_p0,
            #                      params={"ormar_p0": "a"})

        Every read that runs a select (``all``, ``get``, ``first``,
        ``iterate``, ``values``, ``exists``, ``count`` and the aggregates)
        goes through here instead of ``build_select_expression``. A statement
        that is not a plain select passes ``wrap`` to build the executed
        statement around the select and ``variant`` to keep its cache key apart
        from the plain select's, e.g. ``count()`` passes
        ``variant=("count", distinct)`` and ``wrap=count_statement``.

        On a cache hit nothing is built: only the cache key and the values are
        collected from the queryset.

        :param variant: how the select is used (plain, count, aggregate, ...)
        :type variant: tuple
        :param limit: number to limit the query
        :type limit: Optional[int]
        :param offset: number to offset by
        :type offset: Optional[int]
        :param order_bys: list of order actions
        :type order_bys: Optional[list]
        :param wrap: turns the built select into the executed statement
        :type wrap: Optional[Callable[[sqlalchemy.sql.Select], Any]]
        :raises QueryDefinitionError: if a ``select_for_update`` queryset runs
            outside a transaction or as count, exists or an aggregate
        :return: statement and values to bind
        :rtype: StatementTemplate
        """
        if self.row_lock:
            if wrap is not None:
                raise QueryDefinitionError(
                    "select_for_update cannot lock count, exists or aggregates, "
                    "use get_or_none() / limit(1).values_list('id') instead."
                )
            if self.model_config.database.get_transaction_connection() is None:
                raise QueryDefinitionError(
                    "select_for_update has to run inside a transaction."
                )
        actions = canonical_actions(
            filter_clauses=self.filter_clauses, exclude_clauses=self.exclude_clauses
        )
        params = template_params(
            actions=actions,
            limit=limit if limit is not None else self.limit_count,
            offset=offset or self.query_offset,
        )
        key = self.select_cache_key(
            variant=variant, limit=limit, offset=offset, order_bys=order_bys
        )
        cache = template_cache_for(model_cls=self.model)
        statement = cache.get(key)
        if statement is None:
            statement = self.build_template_statement(
                actions=actions,
                limit=limit,
                offset=offset,
                order_bys=order_bys,
                wrap=wrap,
            )
            cache.put(key=key, statement=statement)
        return StatementTemplate(statement=statement, params=params)

    def build_template_statement(
        self,
        actions: list,
        limit: Optional[int],
        offset: Optional[int],
        order_bys: Optional[list],
        wrap: Optional[Callable[[sqlalchemy.sql.Select], Any]],
    ) -> Any:
        """
        Build the read statement of a new cache key with named value slots, the
        statement that is then cached.

        The select is built by ``build_select_expression`` as usual, but with a
        ``SlotBinder`` that turns every filter value, the limit and the offset
        into a named bind parameter. ``wrap`` then builds the executed statement
        around it, and the values of this first call are cleared from the
        result (see ``release_values``).

        :param actions: filter actions in canonical order
        :type actions: list
        :param limit: number to limit the query
        :type limit: Optional[int]
        :param offset: number to offset by
        :type offset: Optional[int]
        :param order_bys: list of order actions
        :type order_bys: Optional[list]
        :param wrap: turns the built select into the executed statement
        :type wrap: Optional[Callable[[sqlalchemy.sql.Select], Any]]
        :return: statement to execute
        :rtype: Any
        """
        binder = SlotBinder(actions=actions)
        select = self.build_select_expression(
            limit=limit, offset=offset, order_bys=order_bys, binder=binder
        )
        statement = wrap(select) if wrap is not None else select
        release_values(statement=statement)
        return statement

    def build_write_template(
        self, statement: type[WriteStatement], values: dict
    ) -> StatementTemplate:
        """
        Return the filtered update or delete of this queryset, or a statement
        of ``update_returning()`` (see ``write_statements``), from the model's
        template cache, with the values to bind::

            Author.objects.filter(score__lt=5).build_write_template(
                statement=UpdateWrite, values={"name": "x"}
            )
            # -> UPDATE authors SET name=:ormar_v0 WHERE authors.score < :ormar_p0
            #    {"ormar_p0": 5, "ormar_v0": "x"}

        The cache key is the statement class, the filter and exclude clauses
        (see ``templates.clauses_cache_key``), the joined relations (filters
        on related models select the matched primary keys through them) and
        the updated column names. Updates and deletes take no ordering or
        limit, so nothing else changes their SQL. Filter values are named by
        ``SlotBinder`` like in reads, updated values like in single-row writes
        (``ormar_v{i}``).

        :param statement: statement class
        :type statement: type[WriteStatement]
        :param values: updated values by column name (empty for delete)
        :type values: dict
        :return: statement and values to bind
        :rtype: StatementTemplate
        """
        actions = canonical_actions(
            filter_clauses=self.filter_clauses, exclude_clauses=self.exclude_clauses
        )
        names = tuple(sorted(values))
        params = template_params(actions=actions, limit=None, offset=None)
        for index, name in enumerate(names):
            params.update(expression_params(value=values[name], slot=f"ormar_v{index}"))
        key = (
            statement,
            clauses_cache_key(clauses=self.filter_clauses),
            clauses_cache_key(clauses=self.exclude_clauses),
            tuple(self._select_related),
            tuple(
                (name, expression_key(node=values[name]))
                if isinstance(values[name], Expression)
                else name
                for name in names
            ),
        )
        cache = template_cache_for(model_cls=self.model)
        cached = cache.get(key)
        if cached is None:
            cached = statement.make(
                model=self.model,
                queryset=self,
                values=values,
                binder=SlotBinder(actions=actions),
            )
            release_values(statement=cached)
            cache.put(key=key, statement=cached)
        return StatementTemplate(statement=cached, params=params)

    def matched_rows_clause(self, binder: Optional[SlotBinder]) -> Any:
        """
        Return the condition keeping the rows this queryset selects, by primary
        key, for an update or delete filtering on related models::

            tracks.id IN (SELECT ormar_matched.id FROM (
                SELECT tracks.id FROM tracks LEFT OUTER JOIN albums AS ... ON ...
                WHERE <filters>
            ) AS ormar_matched)

        The select is wrapped in a derived table, as MySQL does not let a
        statement select from the table it updates or deletes from (error
        1093). A composite primary key is compared as a tuple.

        :param binder: names filter values for templates, None binds them as
            plain values
        :type binder: Optional[SlotBinder]
        :return: condition on the primary key columns
        :rtype: Any
        """
        matched = (
            Query(
                model_cls=self.model,
                filter_clauses=self.filter_clauses,
                exclude_clauses=self.exclude_clauses,
                select_related=self._select_related,
                limit_count=None,
                offset=None,
                excludable=self._excludable,
                order_bys=None,
                limit_raw_sql=False,
                binder=binder,
            )
            .build_primary_key_select()
            .subquery("ormar_matched")
        )
        return self.model_config.pk.row_value().in_(sqlalchemy.select(*matched.c))

    def limit_cache_key(self, limit: Optional[int]) -> tuple:
        """
        Return how the effective limit changes the SQL: whether a LIMIT is
        applied at all, and whether it is non-zero (only a non-zero limit with
        ``select_related`` builds the pagination subquery). The limit value
        itself is bound, so ``limit(5)`` and ``limit(10)`` share a statement::

            limit(None) -> (False, False)
            limit(0)    -> (True, False)
            limit(10)   -> (True, True)

        :param limit: limit passed to ``build_select_expression``
        :type limit: Optional[int]
        :return: limit presence and truthiness
        :rtype: tuple
        """
        effective = limit if limit is not None else self.limit_count
        return effective is not None, bool(effective)

    def select_cache_key(
        self,
        variant: tuple,
        limit: Optional[int],
        offset: Optional[int],
        order_bys: Optional[list],
    ) -> tuple:
        """
        Return the cache key of the statement ``build_select_expression`` would build
        with the given arguments: everything that changes its SQL text and none
        of the bound values. Two querysets with the same key must build the
        same SQL, or one would run the other's statement, so each part covers
        one input of the build:

        * ``variant`` - plain select, exists, count or aggregate
        * filter and exclude clauses - see ``clauses_cache_key``
        * ``select_related`` - the joins
        * selected fields - see ``excludable_cache_key``
        * ordering - see ``order_cache_key``
        * limit and offset presence - see ``limit_cache_key``
        * ``limit_raw_sql`` - limit on raw rows instead of main models
        * ``row_lock`` - the ``select_for_update`` options

        Any new queryset option that changes the built SQL has to be added
        here; the cross check of the test suite fails when one is missing.

        :param variant: how the select is used (plain, count, aggregate, ...)
        :type variant: tuple
        :param limit: limit passed to ``build_select_expression``
        :type limit: Optional[int]
        :param offset: offset passed to ``build_select_expression``
        :type offset: Optional[int]
        :param order_bys: order actions passed to ``build_select_expression``
        :type order_bys: Optional[list]
        :return: hashable cache key of the statement
        :rtype: tuple
        """
        return (
            variant,
            clauses_cache_key(clauses=self.filter_clauses),
            clauses_cache_key(clauses=self.exclude_clauses),
            tuple(self._select_related),
            excludable_cache_key(excludable=self._excludable),
            order_cache_key(order_bys=order_bys or self.order_bys),
            self.limit_cache_key(limit=limit),
            bool(offset or self.query_offset),
            self.limit_sql_raw,
            tuple(self.row_lock.items()),
        )

    def filter(  # noqa: A003
        self, *args: Any, _exclude: bool = False, **kwargs: Any
    ) -> "QuerySet[T]":
        """
        Allows you to filter by any `Model` attribute/field
        as well as to fetch instances, with a filter across an FK relationship.

        You can use special filter suffix to change the filter operands:

        *  exact - like `album__name__exact='Malibu'` (exact match)
        *  iexact - like `album__name__iexact='malibu'` (exact match case insensitive)
        *  contains - like `album__name__contains='Mal'` (sql like)
        *  icontains - like `album__name__icontains='mal'` (sql like case insensitive)
        *  in - like `album__name__in=['Malibu', 'Barclay']` (sql in)
        *  isnull - like `album__name__isnull=True` (sql is null)
           (isnotnull `album__name__isnull=False` (sql is not null))
        *  gt - like `position__gt=3` (sql >)
        *  gte - like `position__gte=3` (sql >=)
        *  lt - like `position__lt=3` (sql <)
        *  lte - like `position__lte=3` (sql <=)
        *  startswith - like `album__name__startswith='Mal'` (exact start match)
        *  istartswith - like `album__name__istartswith='mal'` (case insensitive)
        *  endswith - like `album__name__endswith='ibu'` (exact end match)
        *  iendswith - like `album__name__iendswith='IBU'` (case insensitive)

        Note that you can also use python style filters - check the docs!

        :param _exclude: flag if it should be exclude or filter
        :type _exclude: bool
        :param kwargs: fields names and proper value types
        :type kwargs: Any
        :return: filtered QuerySet
        :rtype: QuerySet
        """
        filter_groups, select_related = self._resolve_filter_groups(groups=args)
        qryclause = QueryClause(
            model_cls=self.model,
            select_related=select_related,
            filter_clauses=self.filter_clauses,
        )
        if _exclude:
            own_clauses, select_related = qryclause.prepare_filter(
                _own_only=True, **kwargs
            )
            if not own_clauses and not filter_groups:
                return self.rebuild_self(select_related=select_related)
            # groups are already resolved, so own actions are attached directly
            exclude_group = FilterGroup(*filter_groups)
            exclude_group.actions = own_clauses
            return self.rebuild_self(
                exclude_clauses=self.exclude_clauses + [exclude_group],
                select_related=select_related,
            )
        filter_clauses, select_related = qryclause.prepare_filter(**kwargs)
        return self.rebuild_self(
            filter_clauses=filter_clauses + filter_groups,  # type: ignore
            select_related=select_related,
        )

    def exclude(self, *args: Any, **kwargs: Any) -> "QuerySet[T]":  # noqa: A003
        """
        Works exactly the same as filter and all modifiers (suffixes) are the same,
        but returns a *not* condition.

        So if you use `filter(name='John')` which is `where name = 'John'` in SQL,
        the `exclude(name='John')` equals to `where name <> 'John'`

        Note that all conditions are joined so if you pass multiple values it
        becomes a union of conditions.

        `exclude(name='John', age>=35)` will become
        `where not (name='John' and age>=35)`

        :param kwargs: fields names and proper value types
        :type kwargs: Any
        :return: filtered QuerySet
        :rtype: QuerySet
        """
        return self.filter(_exclude=True, *args, **kwargs)

    def select_related(self, related: Union[list, str, FieldAccessor]) -> "QuerySet[T]":
        """
        Allows to prefetch related models during the same query.

        **With `select_related` always only one query is run against the database**,
        meaning that one (sometimes complicated) join is generated and later nested
        models are processed in python.

        To fetch related model use `ForeignKey` names.

        To chain related `Models` relation use double underscores between names.

        :param related: list of relation field names, can be linked by '__' to nest
        :type related: Union[list, str]
        :return: QuerySet
        :rtype: QuerySet
        """
        if not isinstance(related, list):
            related = [related]
        related = cast(list, extract_access_chains(related))

        related = sorted(list(set(list(self._select_related) + related)))
        return self.rebuild_self(select_related=related)

    def select_all(
        self,
        follow: bool = False,
        max_depth: Optional[int] = None,
        follow_reverse: Union[bool, int] = 0,
    ) -> "QuerySet[T]":
        """
        By default adds only directly related models.

        If follow=True is set it adds also related models of related models.

        To not get stuck in an infinite loop as related models also keep a relation
        to parent model visited models set is kept.

        That way already visited models that are nested are loaded, but the load do not
        follow them inside. So Model A -> Model B -> Model C -> Model A -> Model X
        will load second Model A but will never follow into Model X.
        Nested relations of those kind need to be loaded manually.

        :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 max_depth: number of relations to follow at most with
            follow=True, forward foreign keys ``DEFAULT_FOLLOW_DEPTH`` (5) deep by
            default (every relation without limit in the deprecated ``map``
            traversal)
        :type max_depth: Optional[int]
        :param follow_reverse: number of first levels where follow=True also
            follows reverse and many to many relations, ``True`` = 1
        :type follow_reverse: Union[bool, int]
        :return: reloaded Model
        :rtype: Model
        """
        relations = list(self.model.extract_related_names())
        if follow:
            relations = self.model._follow_relation_paths(
                max_depth=max_depth, follow_reverse=follow_reverse
            )
        return self.rebuild_self(select_related=relations)

    def prefetch_related(
        self, related: Union[list, str, FieldAccessor, Prefetch]
    ) -> "QuerySet[T]":
        """
        Allows to prefetch related models during query - but opposite to
        `select_related` each subsequent model is fetched in a separate database query.

        **With `prefetch_related` always one query per Model is run against the
        database**, meaning that you will have multiple queries executed one
        after another.

        To fetch related model use `ForeignKey` names.

        To chain related `Models` relation use double underscores between names.

        :param related: list of relation field names, can be linked by '__' to nest
        :type related: Union[list, str]
        :return: QuerySet
        :rtype: QuerySet
        """
        if not isinstance(related, list):
            related = [related]
        querysets = dict(self._prefetch_querysets)
        for item in related:
            if isinstance(item, Prefetch):
                if not isinstance(item.queryset, QuerySet):
                    raise QueryDefinitionError(
                        f"Prefetch queryset must be a QuerySet, got {item.queryset!r}."
                    )
                (path,) = extract_access_chains([item.relation])
                querysets[path] = item.queryset
        related = [
            item.relation if isinstance(item, Prefetch) else item for item in related
        ]
        related = cast(list, extract_access_chains(related))

        related = list(set(list(self._prefetch_related) + related))
        return self.rebuild_self(prefetch_related=related, prefetch_querysets=querysets)

    def flatten_fields(
        self,
        columns: Union[list, str, set, tuple, dict, FieldAccessor],
    ) -> "QuerySet[T]":
        """
        Render selected related models as their primary-key value on
        ``model_dump()`` instead of the default nested dict.

        Accepts the same input forms as :py:meth:`fields` / :py:meth:`exclude_fields`
        plus ``FieldAccessor`` / list of accessors. Missing relations are
        auto-loaded: single-valued foreign keys go into ``select_related``,
        many-to-many and reverse relations into ``prefetch_related``.

        Chained calls merge. A flatten directive conflicts with any include or
        exclude sub-field selection on the same relation (scalar output has no
        place for children).

        :param columns: relations to flatten on serialization
        :type columns: Union[list, str, set, tuple, dict, FieldAccessor]
        :return: new QuerySet with the flatten spec applied
        :rtype: QuerySet[T]
        """
        normalized = extract_access_chains(columns)

        excludable = ormar.ExcludableItems.from_excludable(self._excludable)
        excludable.build(
            items=normalized,
            model_cls=self.model_cls,  # type: ignore
            slot="flatten",
        )
        excludable.validate_flatten_vs_excludable(
            source_model=self.model_cls  # type: ignore
        )

        select_to_add, prefetch_to_add = self._classify_flatten_paths(
            excludable._flatten_paths
        )
        new_select = sorted(set(self._select_related) | select_to_add)
        new_prefetch = sorted(set(self._prefetch_related) | prefetch_to_add)
        return self.rebuild_self(
            excludable=excludable,
            select_related=new_select,
            prefetch_related=new_prefetch,
        )

    def _classify_flatten_paths(
        self, paths: Iterable[tuple[str, ...]]
    ) -> tuple[set[str], set[str]]:
        """
        Split flatten tuple paths into ``select_related`` (single-valued FK,
        incl. self-ref) and ``prefetch_related`` (m2m / reverse) buckets so
        the caller can auto-add whichever the user hasn't loaded already.

        :param paths: pre-split tuple paths collected during flatten build
        :type paths: Iterable[tuple[str, ...]]
        :return: (paths for select_related, paths for prefetch_related) — each
            as dunder strings for downstream ``select_related`` /
            ``prefetch_related`` call sites
        :rtype: tuple[set[str], set[str]]
        """
        select_paths: set[str] = set()
        prefetch_paths: set[str] = set()
        source_model = self.model
        for parts in paths:
            parent_model: type["Model"] = source_model
            if len(parts) > 1:
                _, parent_model, _, _ = get_relationship_alias_model_and_str(
                    source_model=source_model,
                    related_parts=list(parts[:-1]),
                )
            field = parent_model.ormar_config.model_fields[parts[-1]]
            bucket = (
                prefetch_paths
                if getattr(field, "is_multi", False) or getattr(field, "virtual", False)
                else select_paths
            )
            bucket.add("__".join(parts))
        return select_paths, prefetch_paths

    def fields(
        self, columns: Union[list, str, set, dict], slot: "Slot" = "include"
    ) -> "QuerySet[T]":
        """
        With `fields()` you can select subset of model columns to limit the data load.

        Note that `fields()` and `exclude_fields()` works both for main models
        (on normal queries like `get`, `all` etc.)
        as well as `select_related` and `prefetch_related`
        models (with nested notation).

        You can select specified fields by passing a `str, list[str], set[str] or
        dict` with nested definition.

        To include related models use notation
        `{related_name}__{column}[__{optional_next} etc.]`.

        `fields()` can be called several times, building up the columns to select.

        If you include related models into `select_related()` call but you won't specify
        columns for those models in fields - implies a list of all fields for
        those nested models.

        Mandatory fields cannot be excluded as it will raise `ValidationError`,
        to exclude a field it has to be nullable.

        Pk column cannot be excluded - it's always auto added even if
        not explicitly included.

        You can also pass fields to include as dictionary or set.

        To mark a field as included in a dictionary use it's name as key
        and ellipsis as value.

        To traverse nested models use nested dictionaries.

        To include fields at last level instead of nested dictionary a set can be used.

        To include whole nested model specify model related field name and ellipsis.

        :param slot: which Excludable slot to write into ("include" or "exclude")
        :type slot: Slot
        :param columns: columns to include
        :type columns: Union[list, str, set, dict]
        :return: QuerySet
        :rtype: QuerySet
        """
        excludable = ormar.ExcludableItems.from_excludable(self._excludable)
        excludable.build(
            items=columns,
            model_cls=self.model_cls,  # type: ignore
            slot=slot,
        )
        if excludable._flatten_paths:
            excludable.validate_flatten_vs_excludable(
                source_model=self.model_cls  # type: ignore
            )

        return self.rebuild_self(excludable=excludable)

    def exclude_fields(self, columns: Union[list, str, set, dict]) -> "QuerySet[T]":
        """
        With `exclude_fields()` you can select subset of model columns that will
        be excluded to limit the data load.

        It's the opposite of `fields()` method so check documentation above
        to see what options are available.

        Especially check above how you can pass also nested dictionaries
        and sets as a mask to exclude fields from whole hierarchy.

        Note that `fields()` and `exclude_fields()` works both for main models
        (on normal queries like `get`, `all` etc.)
        as well as `select_related` and `prefetch_related` models
        (with nested notation).

        Mandatory fields cannot be excluded as it will raise `ValidationError`,
        to exclude a field it has to be nullable.

        Pk column cannot be excluded - it's always auto added even
        if explicitly excluded.

        :param columns: columns to exclude
        :type columns: Union[list, str, set, dict]
        :return: QuerySet
        :rtype: QuerySet
        """
        return self.fields(columns=columns, slot="exclude")

    def order_by(
        self, columns: Union[list, str, OrderAction, RandomOrder, Random]
    ) -> "QuerySet[T]":
        """
        With `order_by()` you can order the results from database based on your
        choice of fields.

        You can provide a string with field name or list of strings with fields names.

        Ordering in sql will be applied in order of names you provide in order_by.

        By default if you do not provide ordering `ormar` explicitly orders by
        all primary keys

        If you are sorting by nested models that causes that the result rows are
        unsorted by the main model `ormar` will combine those children rows into
        one main model.

        The main model will never duplicate in the result

        To order by main model field just provide a field name

        To sort on nested models separate field names with dunder '__'.

        You can sort this way across all relation types -> `ForeignKey`,
        reverse virtual FK and `ManyToMany` fields.

        To sort in descending order provide a hyphen in front of the field name

        To sort randomly provide ``"?"``, ``ormar.random()`` or ``ormar.Random()``

        :param columns: columns by which models should be sorted
        :type columns: Union[list, str]
        :return: QuerySet
        :rtype: QuerySet
        """
        if not isinstance(columns, list):
            columns = [columns]
        orders_by = expand_pk_orders(model_cls=self.model, columns=columns)

        order_bys = self.order_bys + [x for x in orders_by if x not in self.order_bys]
        return self.rebuild_self(order_bys=order_bys)

    async def values(
        self,
        fields: Union[list, str, set, dict, None] = None,
        exclude_through: bool = False,
        _as_dict: bool = True,
        _flatten: bool = False,
    ) -> list:
        """
        Return a list of dictionaries with column values in order of the fields
        passed or all fields from queried models.

        To filter for given row use filter/exclude methods before values,
        to limit number of rows use limit/offset or paginate before values.

        Note that it always return a list even for one row from database.

        :param exclude_through: flag if through models should be excluded
        :type exclude_through: bool
        :param _flatten: internal parameter to flatten one element tuples
        :type _flatten: bool
        :param _as_dict: internal parameter if return dict or tuples
        :type _as_dict: bool
        :param fields: field name or list of field names to extract from db
        :type fields:  Union[list, str, set, dict]
        """
        if fields:
            return await self.fields(columns=fields).values(
                _as_dict=_as_dict, _flatten=_flatten, exclude_through=exclude_through
            )
        missing_joins = self._excludable.included_relation_paths().difference(
            self._select_related
        )
        if missing_joins:
            return await self.select_related(related=sorted(missing_joins)).values(
                _as_dict=_as_dict, _flatten=_flatten, exclude_through=exclude_through
            )
        excludable = self._excludable.with_projection_exclusions(
            source_model=self.model,
            select_related=self._select_related,
        )
        projected = (
            self
            if excludable is self._excludable
            else self.rebuild_self(excludable=excludable)
        )
        template = projected.build_select_template()
        async with self.model_config.database.get_query_executor() as executor:
            rows = await executor.fetch_all(template.statement, template.params)
        if not rows:
            return []
        columns = values_column_map(
            model_cls=self.model_cls,  # type: ignore
            select_related=self._select_related,
            excludable=excludable,
            exclude_through=exclude_through,
            column_names=list(rows[0].keys()),  # type: ignore
        )
        result = extract_values(rows=rows, columns=columns, as_dict=_as_dict)
        if _as_dict:
            return result
        if _flatten and self._excludable.include_entry_count() != 1:
            raise QueryDefinitionError(
                "You cannot flatten values_list if more than one field is selected!"
            )
        return result if not _flatten else [x[0] for x in result]

    async def values_list(
        self,
        fields: Union[list, str, set, dict, None] = None,
        flatten: bool = False,
        exclude_through: bool = False,
    ) -> list:
        """
        Return a list of tuples with column values in order of the fields passed or
        all fields from queried models.

        When one field is passed you can flatten the list of tuples into list of values
        of that single field.

        To filter for given row use filter/exclude methods before values,
        to limit number of rows use limit/offset or paginate before values.

        Note that it always return a list even for one row from database.

        :param exclude_through: flag if through models should be excluded
        :type exclude_through: bool
        :param fields: field name or list of field names to extract from db
        :type fields: Union[str, list[str]]
        :param flatten: when one field is passed you can flatten the list of tuples
        :type flatten: bool
        """
        return await self.values(
            fields=fields,
            exclude_through=exclude_through,
            _as_dict=False,
            _flatten=flatten,
        )

    async def exists(self) -> bool:
        """
        Returns a bool value to confirm if there are rows matching the given criteria
        (applied with `filter` and `exclude` if set).

        :return: result of the check
        :rtype: bool
        """
        template = self.build_select_template(
            variant=("exists",), wrap=exists_statement
        )
        async with self.model_config.database.get_query_executor() as executor:
            result = await executor.fetch_val(
                query=template.statement, params=template.params
            )
            return bool(result)

    async def count(self, distinct: bool = True) -> int:
        """
        Returns number of rows matching the given criteria
        (applied with `filter` and `exclude` if set before).
        If `distinct` is `True` (the default), this will return
        the number of primary rows selected. If `False`,
        the count will be the total number of rows returned
        (including extra rows for `one-to-many` or `many-to-many`
        left `select_related` table joins).
        `False` is the legacy (buggy) behavior for workflows that depend on it.

        :param distinct: flag if the primary table rows should be distinct or not

        :return: number of rows
        :rtype: int
        """
        wrap = functools.partial(
            count_statement,
            distinct=distinct,
            pk_column_names=self.model_config.pk.column_aliases(),
        )
        template = self.build_select_template(variant=("count", distinct), wrap=wrap)
        async with self.model_config.database.get_query_executor() as executor:
            result = await executor.fetch_val(
                query=template.statement, params=template.params
            )
            return int(result) if result is not None else 0

    async def _query_aggr_function(self, func_name: str, columns: list) -> Any:
        func = getattr(sqlalchemy.func, func_name)
        select_actions = [
            SelectAction(select_str=column, model_cls=self.model) for column in columns
        ]
        if func_name in ["sum", "avg"]:
            if any(not x.is_numeric for x in select_actions):
                raise QueryDefinitionError(
                    "You can use sum and svg only with numeric types of columns"
                )
        if any(x.field_name not in x.target_model.model_fields for x in select_actions):
            raise QueryDefinitionError(
                "You can use aggregate functions only on "
                "existing columns of the target model"
            )
        select_columns = [x.apply_func(func, use_label=True) for x in select_actions]
        wrap = functools.partial(
            aggregate_statement, func_name=func_name, select_columns=select_columns
        )
        template = self.build_select_template(
            variant=("aggregate", func_name, tuple(columns)), wrap=wrap
        )
        async with self.model_config.database.get_query_executor() as executor:
            result = await executor.fetch_one(
                query=template.statement, params=template.params
            )
        values_by_column = dict(zip(columns, result.values()))  # type: ignore
        return values_by_column if len(columns) > 1 else values_by_column[columns[0]]

    async def max(self, columns: Union[str, list[str]]) -> Any:  # noqa: A003
        """
        Returns max value of columns for rows matching the given criteria
        (applied with `filter` and `exclude` if set before).

        :return: max value of column(s)
        :rtype: Any
        """
        if not isinstance(columns, list):
            columns = [columns]
        return await self._query_aggr_function(func_name="max", columns=columns)

    async def min(self, columns: Union[str, list[str]]) -> Any:  # noqa: A003
        """
        Returns min value of columns for rows matching the given criteria
        (applied with `filter` and `exclude` if set before).

        :return: min value of column(s)
        :rtype: Any
        """
        if not isinstance(columns, list):
            columns = [columns]
        return await self._query_aggr_function(func_name="min", columns=columns)

    async def sum(self, columns: Union[str, list[str]]) -> Any:  # noqa: A003
        """
        Returns sum value of columns for rows matching the given criteria
        (applied with `filter` and `exclude` if set before).

        :return: sum value of columns
        :rtype: int
        """
        if not isinstance(columns, list):
            columns = [columns]
        return await self._query_aggr_function(func_name="sum", columns=columns)

    async def avg(self, columns: Union[str, list[str]]) -> Any:
        """
        Returns avg value of columns for rows matching the given criteria
        (applied with `filter` and `exclude` if set before).

        :return: avg value of columns
        :rtype: Union[int, float, list]
        """
        if not isinstance(columns, list):
            columns = [columns]
        return await self._query_aggr_function(func_name="avg", columns=columns)

    def _filters_read_related(self) -> bool:
        """
        :return: whether a filter or exclude clause reads a related model, by
            its key or by an expression
        :rtype: bool
        """
        for clause in self.filter_clauses + self.exclude_clauses:
            actions = clause._iter() if isinstance(clause, FilterGroup) else [clause]
            for action in actions:
                if any(path.related_parts for path in action.path_actions()):
                    return True
        return False

    async def update(self, each: bool = False, **kwargs: Any) -> int:
        """
        Updates the model table after applying the filters from kwargs.

        You have to either pass a filter to narrow down a query or explicitly pass
        each=True flag to affect whole table.

        Filters on related models (``filter(album__name="A")``) are supported,
        the update touches the rows the same filters select in ``all()`` (limit
        and offset do not apply). Expressions may read fields of models reached
        through foreign keys (``position=F("album__rank")``); rows without a
        related row on such a path are not updated and not counted.

        :param each: flag if whole table should be affected if no filter is passed
        :type each: bool
        :param kwargs: fields names and proper value types, or column expressions
            (``taken=Slot.taken + 1``, ``position=F("album__rank")``)
        :type kwargs: Any
        :raises QueryDefinitionError: if an expression sets a relation, reads a
            reverse or many to many relation or reads another column set by
            this update
        :return: number of updated rows
        :rtype: int
        """
        updates = self.update_values(each=each, values=kwargs)
        template = self.build_write_template(statement=UpdateWrite, values=updates)
        async with self.model_config.database.get_query_executor() as executor:
            return await executor.execute(template.statement, template.params)

    async def update_returning(self, each: bool = False, **kwargs: Any) -> list["T"]:
        """
        Updates the rows like ``update()`` and returns them as stored after the
        update::

            expired = await Booking.objects.filter(status="waitlist").update_returning(
                status="expired"
            )

        The models hold the columns of the model's own table only: relations
        are not loaded, foreign keys are models with only the primary key set,
        like ``all()`` without ``select_related``. ``fields()``,
        ``select_related()`` and the ordering of the queryset do not apply,
        the rows come back in no particular order. No signals are sent.

        PostgreSQL and SQLite (3.35+) run one ``UPDATE ... RETURNING``. MySQL
        has no ``RETURNING``: in the open transaction, or a new one, the rows
        are selected ``FOR UPDATE``, updated and read back by primary key.

        :param each: flag if whole table should be affected if no filter is passed
        :type each: bool
        :param kwargs: fields names and proper value types, or column expressions
        :type kwargs: Any
        :raises QueryDefinitionError: like ``update()``
        :return: updated models
        :rtype: list[Model]
        """
        updates = self.update_values(each=each, values=kwargs)
        database = self.model_config.database
        if database.rules.update_returning:
            template = self.build_write_template(
                statement=UpdateReturningWrite, values=updates
            )
            async with database.get_query_executor() as executor:
                rows = await executor.fetch_all(template.statement, template.params)
        else:
            rows = await self.update_locked_rows(updates=updates)
        return await QuerySet(model_cls=self.model)._process_query_result_rows(rows)

    async def update_locked_rows(self, updates: dict) -> list:
        """
        Update the rows of ``update_returning()`` without ``RETURNING``, in the
        open transaction or a new one, and return them as stored::

            SELECT tracks.id FROM tracks WHERE <filters> FOR UPDATE OF tracks
            UPDATE tracks SET ... WHERE tracks.id IN (<locked keys>)
            SELECT tracks.* FROM tracks WHERE tracks.id IN (<locked keys>) FOR UPDATE

        The lock keeps other transactions from changing the rows in between,
        and the locking read back sees the latest committed versions (not the
        snapshot of a REPEATABLE READ transaction), so the rows read back are
        the rows as this update left them.

        :param updates: updated values by column name
        :type updates: dict
        :return: rows of the updated models
        :rtype: list
        """
        lock = self.build_write_template(statement=LockWrite, values=updates)
        update = self.build_write_template(statement=UpdateLockedWrite, values=updates)
        aliases = self.model_config.pk.column_aliases()
        async with self.model_config.database.get_query_executor(
            transactional=True
        ) as executor:
            locked = await executor.fetch_all(lock.statement, lock.params)
            if not locked:
                return []
            keys = [tuple(row[alias] for alias in aliases) for row in locked]
            if len(aliases) == 1:
                keys = [key[0] for key in keys]
            await executor.execute(update.statement, {**update.params, PKS_SLOT: keys})
            rows = row_template(statement=RowsLockWrite, model_cls=self.model, pk=keys)
            return await executor.fetch_all(rows.statement, rows.params)

    def update_values(self, each: bool, values: dict) -> dict:
        """
        Check an ``update()`` and turn its keyword arguments into the values
        to write, by column name: own fields only, ``on_update`` values added,
        plain values validated and converted, expressions as expression nodes.

        :param each: flag if whole table should be affected if no filter is passed
        :type each: bool
        :param values: keyword arguments of the update
        :type values: dict
        :raises QueryDefinitionError: if the queryset has no filters and
            ``each`` is not set, or an expression is not allowed (see
            ``update()``)
        :return: values to write by column name
        :rtype: dict
        """
        self.model.verify_writable()
        if not each and not (self.filter_clauses or self.exclude_clauses):
            raise QueryDefinitionError(
                "You cannot update without filtering the queryset first. "
                "If you want to update all rows pass each=True."
            )

        self_fields = self.model.extract_db_own_fields().union(
            self.model.extract_related_names()
        )
        updates = {
            field_name: value
            for field_name, value in values.items()
            if field_name in self_fields
        }
        updates = self.model.populate_onupdate_value(updates)
        expressions = {
            field_name: value._node()
            for field_name, value in updates.items()
            if isinstance(value, Expression)
        }
        for name, node in expressions.items():
            columns = expression_columns(node=node, model=self.model)
            for column in columns.values():
                # only validates the path here, the joins are built with the statement
                forward_join_conditions(model=self.model, path=column.related_parts)
            read = [
                column.field_name
                for column in columns.values()
                if not column.related_parts
            ]
            if name in self.model.extract_related_names() or any(
                field != name and field in updates for field in read
            ):
                raise QueryDefinitionError(
                    f"update() cannot set '{name}' from an expression reading "
                    f"{read}: expressions set no relations and read no columns "
                    f"set by the same update."
                )
        updates = self.model.validate_update_values(
            {
                field_name: value
                for field_name, value in updates.items()
                if field_name not in expressions
            }
        )
        updates = self.model.reconvert_str_to_bytes(updates)
        updates = self.model.translate_columns_to_aliases({**updates, **expressions})
        unconsumed = [name for name in updates if name not in self.table.c]
        if unconsumed:
            raise sqlalchemy.exc.CompileError(
                f"Unconsumed column names: {', '.join(unconsumed)}"
            )
        return updates

    async def delete(self, *args: Any, each: bool = False, **kwargs: Any) -> int:
        """
        Deletes from the model table after applying the filters from kwargs.

        You have to either pass a filter to narrow down a query or explicitly pass
        each=True flag to affect whole table.

        Filters on related models (``filter(training__instructor=instructor)``)
        are supported, the delete removes the rows the same filters select in
        ``all()`` (limit and offset do not apply).

        :param each: flag if whole table should be affected if no filter is passed
        :type each: bool
        :param kwargs: fields names and proper value types
        :type kwargs: Any
        :return: number of deleted rows
        :rtype: int
        """
        self.model.verify_writable()
        if kwargs or args:
            return await self.filter(*args, **kwargs).delete()
        if not each and not (self.filter_clauses or self.exclude_clauses):
            raise QueryDefinitionError(
                "You cannot delete without filtering the queryset first. "
                "If you want to delete all rows use delete(each=True)"
            )
        template = self.build_write_template(statement=DeleteWrite, values={})
        async with self.model_config.database.get_query_executor() as executor:
            return await executor.execute(template.statement, template.params)

    def paginate(self, page: int, page_size: int = 20) -> "QuerySet[T]":
        """
        You can paginate the result which is a combination of offset and limit clauses.
        Limit is set to page size and offset is set to (page-1) * page_size.

        :param page_size: numbers of items per page
        :type page_size: int
        :param page: page number
        :type page: int
        :return: QuerySet
        :rtype: QuerySet
        """
        if page < 1 or page_size < 1:
            raise QueryDefinitionError("Page size and page have to be greater than 0.")

        limit_count = page_size
        query_offset = (page - 1) * page_size
        return self.rebuild_self(limit_count=limit_count, offset=query_offset)

    def select_for_update(
        self,
        nowait: bool = False,
        skip_locked: bool = False,
        read: bool = False,
        no_key: bool = False,
    ) -> "QuerySet[T]":
        """
        Lock the rows of the main model read by this queryset until the end of
        the transaction (``SELECT ... FOR UPDATE OF <table>``). It has to run
        inside a transaction; joined related models are not locked and SQLite
        runs the query without locks.

        :param nowait: raise instead of waiting for rows locked by others
        :type nowait: bool
        :param skip_locked: skip rows locked by others instead of waiting
        :type skip_locked: bool
        :param read: take a shared lock (``FOR SHARE``)
        :type read: bool
        :param no_key: weaker PostgreSQL lock that does not block inserts of
            rows referencing the locked ones (``FOR NO KEY UPDATE`` /
            ``FOR KEY SHARE``)
        :type no_key: bool
        :raises QueryDefinitionError: if both nowait and skip_locked are set
        :return: QuerySet
        :rtype: QuerySet
        """
        if nowait and skip_locked:
            raise QueryDefinitionError("Use either nowait or skip_locked, not both.")
        return self.rebuild_self(
            row_lock={
                "nowait": nowait,
                "skip_locked": skip_locked,
                "read": read,
                "key_share": no_key,
            }
        )

    def limit(
        self, limit_count: int, limit_raw_sql: Optional[bool] = None
    ) -> "QuerySet[T]":
        """
        You can limit the results to desired number of parent models.

        To limit the actual number of database query rows instead of number of main
        models use the `limit_raw_sql` parameter flag, and set it to `True`.

        :param limit_raw_sql: flag if raw sql should be limited
        :type limit_raw_sql: bool
        :param limit_count: number of models to limit
        :type limit_count: int
        :return: QuerySet
        :rtype: QuerySet
        """
        limit_raw_sql = self.limit_sql_raw if limit_raw_sql is None else limit_raw_sql
        return self.rebuild_self(limit_count=limit_count, limit_raw_sql=limit_raw_sql)

    def offset(
        self, offset: int, limit_raw_sql: Optional[bool] = None
    ) -> "QuerySet[T]":
        """
        You can also offset the results by desired number of main models.

        To offset the actual number of database query rows instead of number of main
        models use the `limit_raw_sql` parameter flag, and set it to `True`.

        :param limit_raw_sql: flag if raw sql should be offset
        :type limit_raw_sql: bool
        :param offset: numbers of models to offset
        :type offset: int
        :return: QuerySet
        :rtype: QuerySet
        """
        limit_raw_sql = self.limit_sql_raw if limit_raw_sql is None else limit_raw_sql
        return self.rebuild_self(offset=offset, limit_raw_sql=limit_raw_sql)

    def _single_row_order_bys(self, reverse: bool) -> list["OrderAction"]:
        """
        Builds the ``order_bys`` list used by :meth:`first` and :meth:`last`.

        A pk-based tiebreaker is prepended only when the user has not
        supplied an ordering on the source model (otherwise the user's
        choice must win). For :meth:`last`, both the pk tiebreaker and the
        user's order_bys are flipped so that ``LIMIT 1`` pulls the tail of
        the user's natural order.

        :param reverse: whether to flip directions for the ``last()`` case
        :type reverse: bool
        :return: combined list of OrderAction objects
        :rtype: list[OrderAction]
        """
        pk_defaults = [
            OrderAction(order_str=field, model_cls=self.model_cls)  # type: ignore
            for field in self.model_config.pk.fields
        ]
        user_orders = self.order_bys
        if reverse:
            pk_defaults = [order.flipped() for order in pk_defaults]
            user_orders = [ob.flipped() for ob in user_orders]
        has_source_order = any(x.is_source_model_order for x in self.order_bys)
        prefix: list["OrderAction"] = [] if has_source_order else pk_defaults
        return prefix + list(user_orders)

    async def _fetch_single(self, order_bys: list["OrderAction"]) -> "T":
        """
        Runs a ``LIMIT 1`` select with the given ``order_bys``, merges results,
        runs any configured prefetch, and enforces the single-row contract
        (raises ``NoMatch`` / ``MultipleMatches``). Shared implementation
        backing :meth:`first` and :meth:`last`.

        :param order_bys: fully-resolved order list to apply to the query
        :type order_bys: list[OrderAction]
        :return: the single fetched model
        :rtype: Model
        """
        template = self.build_select_template(limit=1, order_bys=order_bys)
        async with self.model_config.database.get_query_executor() as executor:
            rows = await executor.fetch_all(template.statement, template.params)
        processed_rows = await self._process_query_result_rows(rows)
        if self._prefetch_related and processed_rows:
            processed_rows = await self._prefetch_related_models(processed_rows, rows)
        self.check_single_result_rows_count(processed_rows)
        return processed_rows[0]  # type: ignore

    async def first(self, *args: Any, **kwargs: Any) -> "T":
        """
        Gets the first row from the db ordered by primary key column ascending.

        Passing args and/or kwargs is a shortcut and equals to calling
        ``filter(*args, **kwargs).first()``.

        The query is always executed with ``LIMIT 1`` so at most one row is
        fetched; use :meth:`get` if you want to assert that the criteria
        match exactly one row.

        :raises NoMatch: if no rows match the criteria
        :param kwargs: fields names and proper value types
        :type kwargs: Any
        :return: returned model
        :rtype: Model
        """
        if kwargs or args:
            return await self.filter(*args, **kwargs).first()
        return await self._fetch_single(self._single_row_order_bys(reverse=False))

    async def first_or_none(self, *args: Any, **kwargs: Any) -> Optional["T"]:
        """
        Gets the first row from the db ordered by primary key column ascending.

        Behaves like :meth:`first` but returns ``None`` instead of raising
        ``NoMatch`` when no row matches.

        :param kwargs: fields names and proper value types
        :type kwargs: Any
        :return: returned model or None
        :rtype: Optional[Model]
        """
        try:
            return await self.first(*args, **kwargs)
        except ormar.NoMatch:
            return None

    async def last(self, *args: Any, **kwargs: Any) -> "T":
        """
        Gets the last row from the db ordered by primary key column descending.

        Complementary to :meth:`first`: the default pk ordering is flipped
        and the top row is returned. Passing args and/or kwargs is a shortcut
        and equals to calling ``filter(*args, **kwargs).last()``.

        The query is always executed with ``LIMIT 1`` so at most one row is
        fetched; use :meth:`get` if you want to assert that the criteria
        match exactly one row.

        :raises NoMatch: if no rows match the criteria
        :param kwargs: fields names and proper value types
        :type kwargs: Any
        :return: returned model
        :rtype: Model
        """
        if kwargs or args:
            return await self.filter(*args, **kwargs).last()
        return await self._fetch_single(self._single_row_order_bys(reverse=True))

    async def last_or_none(self, *args: Any, **kwargs: Any) -> Optional["T"]:
        """
        Gets the last row from the db ordered by primary key column descending.

        Behaves like :meth:`last` but returns ``None`` instead of raising
        ``NoMatch`` when no row matches.

        :param kwargs: fields names and proper value types
        :type kwargs: Any
        :return: returned model or None
        :rtype: Optional[Model]
        """
        try:
            return await self.last(*args, **kwargs)
        except ormar.NoMatch:
            return None

    async def get_or_none(self, *args: Any, **kwargs: Any) -> Optional["T"]:
        """
        Gets a single row from the db matching the criteria set by args/kwargs.

        Behaves like :meth:`get` but returns ``None`` instead of raising
        ``NoMatch`` when no row matches. ``MultipleMatches`` is still raised
        when criteria are provided and more than one row matches.

        :raises MultipleMatches: when criteria are set (via ``filter``/``exclude``
            or args/kwargs) and more than one row matches them.
        :param kwargs: fields names and proper value types
        :type kwargs: Any
        :return: returned model or None
        :rtype: Optional[Model]
        """
        try:
            return await self.get(*args, **kwargs)
        except ormar.NoMatch:
            return None

    async def get(self, *args: Any, **kwargs: Any) -> "T":  # noqa: CCR001
        """
        Gets a single row from the db matching the criteria set by args/kwargs.

        Passing args/kwargs is a shortcut for ``filter(*args, **kwargs).get()``.

        When criteria are set (either through args/kwargs here or via a
        chained :meth:`filter`/:meth:`exclude`) the query fetches every
        matching row and asserts that exactly one comes back — ``NoMatch``
        is raised when none match and ``MultipleMatches`` when more than one
        matches.

        When no criteria are set, ``get()`` falls back to returning the last
        row of the table ordered by primary key descending (``LIMIT 1``); in
        that mode ``MultipleMatches`` cannot be raised.

        :raises NoMatch: if no rows match the criteria
        :raises MultipleMatches: when criteria are set and more than one row
            matches them.
        :param kwargs: fields names and proper value types
        :type kwargs: Any
        :return: returned model
        :rtype: Model
        """
        if kwargs or args:
            return await self.filter(*args, **kwargs).get()

        if not (self.filter_clauses or self.exclude_clauses):
            template = self.build_select_template(
                limit=1,
                order_bys=(
                    [
                        OrderAction(
                            order_str=f"-{field}",
                            model_cls=self.model_cls,  # type: ignore
                        )
                        for field in self.model_config.pk.fields
                    ]
                    if not any([x.is_source_model_order for x in self.order_bys])
                    else []
                )
                + self.order_bys,
            )
        else:
            template = self.build_select_template()

        async with self.model_config.database.get_query_executor() as executor:
            rows = await executor.fetch_all(template.statement, template.params)
        processed_rows = await self._process_query_result_rows(rows)
        if self._prefetch_related and processed_rows:
            processed_rows = await self._prefetch_related_models(processed_rows, rows)
        self.check_single_result_rows_count(processed_rows)
        return processed_rows[0]  # type: ignore

    async def get_or_create(
        self,
        _defaults: Optional[dict[str, Any]] = None,
        *args: Any,
        **kwargs: Any,
    ) -> tuple["T", bool]:
        """
        Combination of create and get methods.

        Tries to get a row meeting the criteria for kwargs
        and if `NoMatch` exception is raised
        it creates a new one with given kwargs and _defaults.

        If a concurrent caller wins the race and creates a matching row
        between this call's ``get`` and ``create``, the ``create`` raises
        ``sqlalchemy.exc.IntegrityError`` and ``get`` is retried once.
        If the retry still finds no row, the original ``IntegrityError`` is
        re-raised because the violation isn't a race but a legitimate
        constraint conflict (e.g. a different unique key). Inside a transaction
        the ``create`` runs in a savepoint, so the transaction stays usable.

        Passing a criteria is actually calling filter(*args, **kwargs) method described
        below.

        :param kwargs: fields names and proper value types
        :type kwargs: Any
        :param _defaults: default values for creating object
        :type _defaults: Optional[dict[str, Any]]
        :return: model instance and a boolean
        :rtype: tuple("T", bool)
        """
        _defaults = _defaults or {}
        return await get_or_create_with_retry(
            database=self.model_config.database,
            get=lambda: self.get(*args, **kwargs),
            create=lambda: self.create(**{**kwargs, **_defaults}),
        )

    async def update_or_create(self, **kwargs: Any) -> "T":
        """
        Updates the model, or in case there is no match in database creates a new one.

        If a pk is supplied but no row exists with that pk, a new row is
        created with the supplied pk and field values rather than raising
        ``NoMatch``.

        :param kwargs: fields names and proper value types
        :type kwargs: Any
        :return: updated or created model
        :rtype: Model
        """
        key = self.model_config.pk
        kwargs = key.expand_pk_kwarg(kwargs=kwargs)
        lookup = key.lookup(kwargs=kwargs)
        if lookup is None:
            return await self.create(**kwargs)
        try:
            model = await self.get(**lookup)
        except NoMatch:
            return await self.create(**kwargs)
        return await model.update(_partial=True, **kwargs)

    async def all(self, *args: Any, **kwargs: Any) -> list["T"]:  # noqa: A003
        """
        Returns all rows from a database for given model for set filter options.

        Passing args and/or kwargs is a shortcut and equals to calling
        `filter(*args, **kwargs).all()`.

        If there are no rows meeting the criteria an empty list is returned.

        :param kwargs: fields names and proper value types
        :type kwargs: Any
        :return: list of returned models
        :rtype: list[Model]
        """
        if kwargs or args:
            return await self.filter(*args, **kwargs).all()

        template = self.build_select_template()
        async with self.model_config.database.get_query_executor() as executor:
            rows = await executor.fetch_all(template.statement, template.params)
        result_rows = await self._process_query_result_rows(rows)
        if self._prefetch_related and result_rows:
            result_rows = await self._prefetch_related_models(result_rows, rows)
        if self._reverse_result:
            result_rows.reverse()

        return result_rows

    async def iterate(  # noqa: A003
        self,
        *args: Any,
        **kwargs: Any,
    ) -> AsyncGenerator["T", None]:
        """
        Return async iterable generator for all rows from a database for given model.

        Passing args and/or kwargs is a shortcut and equals to calling
        `filter(*args, **kwargs).iterate()`.

        If there are no rows meeting the criteria an empty async generator is returned.

        :param kwargs: fields names and proper value types
        :type kwargs: Any
        :return: asynchronous iterable generator of returned models
        :rtype: AsyncGenerator[Model]
        """

        if self._prefetch_related:
            raise QueryDefinitionError(
                "Prefetch related queries are not supported in iterators"
            )

        if kwargs or args:
            async for result in self.filter(*args, **kwargs).iterate():
                yield result
            return

        template = self.build_select_template()

        rows: list = []
        last_primary_key = None
        read_pk = self.model_config.pk.getter(
            keys=self.model_config.pk.column_aliases()
        )
        # Single shared cache across all yielded chunks so 1-row chunks
        # (the common iterate case) still amortize the plan build.
        plan_cache: dict = {}

        # Server-side cursor (asyncpg/aiomysql) requires an open transaction,
        # which AUTOCOMMIT does not provide.
        async with self.model_config.database.get_query_executor(
            transactional=True
        ) as executor:
            async for row in executor.iterate(template.statement, template.params):
                current_primary_key = read_pk(row)
                if last_primary_key == current_primary_key or last_primary_key is None:
                    last_primary_key = current_primary_key
                    rows.append(row)
                    continue

                yield (await self._process_query_result_rows(rows, plan_cache))[0]
                last_primary_key = current_primary_key
                rows = [row]

            if rows:
                yield (await self._process_query_result_rows(rows, plan_cache))[0]

    @overload
    async def create(
        self, *, on_conflict: Literal["ignore"], **kwargs: Any
    ) -> Optional["T"]: ...

    @overload
    async def create(
        self,
        *,
        on_conflict: Literal["update"],
        conflict_target: Optional[list[str]] = None,
        update_fields: Optional[list[str]] = None,
        update_values: Optional[dict[str, Any]] = None,
        **kwargs: Any,
    ) -> "T": ...

    @overload
    async def create(self, *, on_conflict: None = None, **kwargs: Any) -> "T": ...

    async def create(
        self,
        *,
        on_conflict: Optional[Literal["ignore", "update"]] = None,
        conflict_target: Optional[list[str]] = None,
        update_fields: Optional[list[str]] = None,
        update_values: Optional[dict[str, Any]] = None,
        **kwargs: Any,
    ) -> Optional["T"]:
        """
        Creates the model instance, saves it in a database and returns the updates model
        (with pk populated if not passed and autoincrement is set).

        The allowed kwargs are `Model` fields names and proper value types.

        With ``on_conflict="ignore"`` a row conflicting with an existing one on
        any unique key is skipped and ``None`` is returned.

        With ``on_conflict="update"`` a row conflicting on ``conflict_target``
        (the primary key by default) is updated instead, in the same statement:
        ``update_fields`` (by default all passed fields but the target and the
        key, none when ``update_values`` are given), ``update_values`` and the
        fields with ``on_update``. The stored row is returned. pre_save and
        post_save are sent in both cases.

        :param on_conflict: ``ignore`` to skip a conflicting row, ``update`` to
            update it
        :type on_conflict: Optional[Literal["ignore", "update"]]
        :param conflict_target: names of the fields of the unique key the row
            conflicts on, only with ``update``
        :type conflict_target: Optional[list[str]]
        :param update_fields: names of the fields updated from the inserted
            row, only with ``update``
        :type update_fields: Optional[list[str]]
        :param update_values: values or expressions set on conflict by field
            name, only with ``update``: ``F("x")`` reads the existing row,
            ``Inserted("x")`` the inserted one
        :type update_values: Optional[dict[str, Any]]
        :param kwargs: fields names and proper value types
        :type kwargs: Any
        :raises QueryDefinitionError: for ``conflict_target``,
            ``update_fields`` or ``update_values`` without
            ``on_conflict="update"``, a target field without a value or invalid
            ``update_values``
        :return: created or stored model, ``None`` when the row was skipped
        :rtype: Optional[Model]
        """
        if (conflict_target or update_fields or update_values) and (
            on_conflict != "update"
        ):
            raise QueryDefinitionError(
                "conflict_target, update_fields and update_values need "
                "on_conflict='update'"
            )
        instance = self.model(**kwargs)
        if on_conflict == "update":
            return await instance._upsert(
                conflict_target=conflict_target,
                update_fields=update_fields,
                update_values=update_values,
            )
        if on_conflict:
            return await instance._save(on_conflict=on_conflict)
        return await instance.save()

    async def bulk_create(
        self,
        objects: list["T"],
        on_conflict: Optional[Literal["ignore", "update"]] = None,
        conflict_target: Optional[list[str]] = None,
        update_fields: Optional[list[str]] = None,
        update_values: Optional[dict[str, Any]] = None,
    ) -> None:
        """
        Performs a bulk create in one database session to speed up the process.

        Allows you to create multiple objects at once.

        A valid list of `Model` objects needs to be passed.

        Objects that provide different sets of fields (e.g. an explicit pk or a
        server_default value) are inserted in separate statements, so generated
        primary keys may not follow the order of the passed list.

        With ``on_conflict="ignore"`` rows conflicting with existing ones on any
        unique key are skipped. With ``on_conflict="update"`` rows conflicting on
        ``conflict_target`` (the primary key by default) update ``update_fields``
        (by default all inserted fields but the target and the key, none when
        ``update_values`` are given), ``update_values`` and fields with
        ``on_update``. Skipped objects are marked as saved too.

        Bulk operations do not send signals.

        :param objects: list of ormar models already initialized and ready to save.
        :type objects: list[Model]
        :param on_conflict: ``ignore`` or ``update`` rows conflicting with
            existing ones
        :type on_conflict: Optional[Literal["ignore", "update"]]
        :param conflict_target: names of the fields of the unique key the rows
            conflict on, only with ``update``
        :type conflict_target: Optional[list[str]]
        :param update_fields: names of the fields updated from the inserted
            rows, only with ``update``
        :type update_fields: Optional[list[str]]
        :param update_values: values or expressions set on conflict by field
            name, the same for every row, only with ``update`` (see ``create``)
        :type update_values: Optional[dict[str, Any]]
        """
        self.model.verify_writable()

        if not objects:
            raise ModelListEmptyError("Bulk create objects are empty!")
        if (conflict_target or update_fields or update_values) and (
            on_conflict != "update"
        ):
            raise QueryDefinitionError(
                "conflict_target, update_fields and update_values need "
                "on_conflict='update'"
            )
        on_update, conflict_values = (
            self.model._conflict_updates(
                update_fields=update_fields, update_values=update_values
            )
            if on_conflict == "update"
            else ({}, {})
        )
        # bound after the VALUES clause, the same for every row
        conflict_params = update_values_params(update_values=conflict_values)
        update_params = {
            **{
                f"ormar_on_update_{column}": value
                for column, value in on_update.items()
            },
            **conflict_params,
        }

        ready_objects = []
        trusted = self.model.flat_row_model()
        for i, obj in enumerate(objects):
            values = dump_for_save(obj=obj) if trusted else obj.model_dump()
            row = obj.prepare_model_to_save(new_kwargs=values)
            obj._verify_key_parts_set(row=row)
            ready_objects.append(row)
            if i % 100 == 99:  # pragma: no cover
                await asyncio.sleep(0)

        # rows with different key sets (explicit vs omitted pk or server_default)
        # need different inserts, so each key set runs its own insert template;
        # anything beyond a single statement (or a lone batch the driver runs
        # atomically) runs in one transaction
        rows_by_keys: dict[frozenset[str], list[dict]] = {}
        for row in ready_objects:
            rows_by_keys.setdefault(frozenset(row), []).append(row)
        database = self.model_config.database
        several_statements = len(rows_by_keys) > 1 or (
            len(ready_objects) > 1 and not database.atomic_execute_many
        )
        on_update_columns = tuple(sorted(on_update))
        # MySQL drivers turn executemany into one multi-row VALUES and leave
        # the binds after it unfilled, so a batch reads the on_update values
        # and update_values literals from user variables set once before it
        update_variables = (
            bool(update_params)
            and not database.rules.execute_many_with_trailing_binds
            and any(len(rows) > 1 for rows in rows_by_keys.values())
        )
        async with database.get_query_executor(
            transactional=several_statements
        ) as executor:
            if update_variables:  # pragma: no cover
                await executor.execute(
                    query=cached_statement(
                        model_cls=self.model,
                        key=(
                            "update_assignment",
                            on_update_columns,
                            update_values_key(update_values=conflict_values),
                        ),
                        builder=build_update_assignment,
                        model=self.model,
                        on_update=on_update_columns,
                        update_values=conflict_values,
                    ),
                    params={
                        **{
                            f"ormar_on_update_{index}": on_update[column]
                            for index, column in enumerate(on_update_columns)
                        },
                        **conflict_params,
                    },
                )
            for rows in rows_by_keys.values():
                names = tuple(sorted(rows[0]))
                # duplicates in one batch: the last wins, only while there is no
                # RETURNING (SQLAlchemy would then send a multi-row VALUES, which
                # PostgreSQL rejects for a row affected twice)
                statement = insert_statement(
                    model_cls=self.model,
                    names=names,
                    on_conflict=on_conflict,
                    conflict_target=conflict_target,
                    update_fields=update_fields,
                    on_update=on_update_columns,
                    update_values=conflict_values,
                    update_variables=update_variables,
                )
                bound_updates = {} if update_variables else update_params
                params = [
                    {**value_params(names=names, values=row), **bound_updates}
                    for row in rows
                ]
                if len(rows) == 1:
                    await executor.execute(query=statement, params=params[0])
                else:
                    await executor.execute_many(query=statement, values=params)

        for obj in objects:
            obj.set_save_status(True)

    async def bulk_update(  # noqa:  CCR001
        self, objects: list["T"], columns: Optional[list[str]] = None
    ) -> None:
        """
        Performs bulk update in one database session to speed up the process.

        Allows you to update multiple instance at once.

        All `Models` passed need to have primary key column populated.

        You can also select which fields to update by passing `columns` list
        as a list of string names.

        Bulk operations do not send signals.

        :param objects: list of ormar models
        :type objects: list[Model]
        :param columns: list of columns to update
        :type columns: list[str]
        """
        self.model.verify_writable()
        if not objects:
            raise ModelListEmptyError("Bulk update objects are empty!")

        ready_objects = []
        persisted_keys: list[Any] = []
        key = self.model_config.pk
        if not columns:
            columns = list(
                self.model.extract_db_own_fields().union(
                    self.model.extract_related_names()
                )
            )

        for field in key.fields:
            if field not in columns:
                columns.append(field)

        onupdate_fields = self.model._onupdate_fields
        for field_name in onupdate_fields:
            if field_name not in columns:
                columns.append(field_name)

        columns = [
            alias
            for field_name in columns
            for alias in self.model.get_column_aliases(field_name=field_name)
        ]

        for i, obj in enumerate(objects):
            explicit_fields = obj.__setattr_fields__
            new_kwargs = obj.model_dump()
            if any(new_kwargs.get(field) is None for field in key.fields):
                raise ModelPersistenceError(
                    "You cannot update unsaved objects. "
                    f"{self.model.__name__} has to have {', '.join(key.fields)} "
                    "filled."
                )
            new_kwargs = obj.populate_onupdate_value(
                new_kwargs, explicit_fields=explicit_fields
            )
            obj.update_from_dict(
                {
                    field_name: new_kwargs[field_name]
                    for field_name in onupdate_fields - explicit_fields
                }
            )
            new_kwargs = obj.prepare_model_to_update(new_kwargs)
            ready_objects.append(
                {"new_" + k: v for k, v in new_kwargs.items() if k in columns}
            )
            persisted_keys.append(obj.persisted_key)
            if i % 100 == 99:  # pragma: no cover
                await asyncio.sleep(0)

        pk_column_names = key.column_aliases()
        table_columns = [c.name for c in self.model_config.table.c]
        keys_moved = any(
            persisted != obj.pk for persisted, obj in zip(persisted_keys, objects)
        )
        where_prefix = "old_" if keys_moved else "new_"
        updated = tuple(
            k
            for k in columns
            if (keys_moved or k not in pk_column_names) and k in table_columns
        )
        if keys_moved:
            for row, persisted in zip(ready_objects, persisted_keys):
                parts = key.flat_parts(value=persisted)
                row.update(
                    {
                        f"old_{alias}": part
                        for alias, part in zip(pk_column_names, parts)
                    }
                )
        expr = cached_statement(
            model_cls=self.model,
            key=("bulk_update", updated, where_prefix),
            builder=BulkUpdateWrite.make,
            model=self.model,
            columns=updated,
            where_prefix=where_prefix,
        )
        # Multi-row execute_many: run in an explicit transaction so all rows
        # share a single COMMIT instead of one per row under AUTOCOMMIT.
        async with self.model_config.database.get_query_executor(
            transactional=True
        ) as executor:
            await executor.execute_many(expr, ready_objects)

        for obj in objects:
            obj.set_save_status(True)
            obj._reset_change_tracking()

        await cast(
            type["Model"], self.model_cls
        ).ormar_config.signals.post_bulk_update.send(
            sender=self.model_cls,  # type: ignore
            instances=objects,
        )

    def __getitem__(self, key: Union[int, slice]) -> "QuerySet[T]":
        """
        Returns a new ``QuerySet`` with LIMIT/OFFSET derived from a Python
        integer index or slice.

        Negative indices and negative slice bounds are translated into a
        reversed-order query plus an in-memory list reversal on ``.all()``,
        so that ``Model.objects[-N:]`` returns the last ``N`` rows in the
        original ordering. Slice shapes that would require a ``COUNT(*)``
        round-trip (a bare ``[:-N]``, or mixed positive/negative bounds) are
        rejected with a ``QueryDefinitionError``; use ``.count()`` combined
        with ``.offset()``/``.limit()`` instead.

        Each call replaces the previous pagination state rather than composing
        with it — subsequent slicing on an already-sliced queryset is not
        guaranteed to compose in a Python-list-like way.

        :param key: integer index or slice
        :type key: int | slice
        :raises QueryDefinitionError: when ``key`` is not an ``int``/``slice``
            or when the slice cannot be expressed without a count
        :return: new QuerySet with updated pagination
        :rtype: QuerySet
        """
        bounds = normalize_slice(key)
        order_bys = self.order_bys
        if self._reverse_result != bounds.reverse:
            if not order_bys:
                order_bys = OrderAction.from_model_defaults(self.model)
            order_bys = [ob.flipped() for ob in order_bys]
        return self.rebuild_self(
            limit_count=bounds.limit,
            offset=bounds.offset,
            order_bys=order_bys,
            reverse_result=bounds.reverse,
        )

model property

Shortcut to model class set on QuerySet.

Returns:

Type Description
type[Model]

model class

model_config property

Shortcut to model class OrmarConfig set on QuerySet model.

Returns:

Type Description
model's OrmarConfig

OrmarConfig of the model

table property

Shortcut to models table from OrmarConfig.

Returns:

Type Description
sqlalchemy.Table

database table

__getitem__(key)

Returns a new QuerySet with LIMIT/OFFSET derived from a Python integer index or slice.

Negative indices and negative slice bounds are translated into a reversed-order query plus an in-memory list reversal on .all(), so that Model.objects[-N:] returns the last N rows in the original ordering. Slice shapes that would require a COUNT(*) round-trip (a bare [:-N], or mixed positive/negative bounds) are rejected with a QueryDefinitionError; use .count() combined with .offset()/.limit() instead.

Each call replaces the previous pagination state rather than composing with it — subsequent slicing on an already-sliced queryset is not guaranteed to compose in a Python-list-like way.

Parameters:

Name Type Description Default
key Union[int, slice]

integer index or slice

required

Returns:

Type Description
QuerySet

new QuerySet with updated pagination

Raises:

Type Description
QueryDefinitionError

when key is not an int/slice or when the slice cannot be expressed without a count

Source code in ormar/queryset/queryset.py
Python
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
def __getitem__(self, key: Union[int, slice]) -> "QuerySet[T]":
    """
    Returns a new ``QuerySet`` with LIMIT/OFFSET derived from a Python
    integer index or slice.

    Negative indices and negative slice bounds are translated into a
    reversed-order query plus an in-memory list reversal on ``.all()``,
    so that ``Model.objects[-N:]`` returns the last ``N`` rows in the
    original ordering. Slice shapes that would require a ``COUNT(*)``
    round-trip (a bare ``[:-N]``, or mixed positive/negative bounds) are
    rejected with a ``QueryDefinitionError``; use ``.count()`` combined
    with ``.offset()``/``.limit()`` instead.

    Each call replaces the previous pagination state rather than composing
    with it — subsequent slicing on an already-sliced queryset is not
    guaranteed to compose in a Python-list-like way.

    :param key: integer index or slice
    :type key: int | slice
    :raises QueryDefinitionError: when ``key`` is not an ``int``/``slice``
        or when the slice cannot be expressed without a count
    :return: new QuerySet with updated pagination
    :rtype: QuerySet
    """
    bounds = normalize_slice(key)
    order_bys = self.order_bys
    if self._reverse_result != bounds.reverse:
        if not order_bys:
            order_bys = OrderAction.from_model_defaults(self.model)
        order_bys = [ob.flipped() for ob in order_bys]
    return self.rebuild_self(
        limit_count=bounds.limit,
        offset=bounds.offset,
        order_bys=order_bys,
        reverse_result=bounds.reverse,
    )

all(*args, **kwargs) async

Returns all rows from a database for given model for set filter options.

Passing args and/or kwargs is a shortcut and equals to calling filter(*args, **kwargs).all().

If there are no rows meeting the criteria an empty list is returned.

Parameters:

Name Type Description Default
kwargs Any

fields names and proper value types

{}

Returns:

Type Description
list[Model]

list of returned models

Source code in ormar/queryset/queryset.py
Python
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
async def all(self, *args: Any, **kwargs: Any) -> list["T"]:  # noqa: A003
    """
    Returns all rows from a database for given model for set filter options.

    Passing args and/or kwargs is a shortcut and equals to calling
    `filter(*args, **kwargs).all()`.

    If there are no rows meeting the criteria an empty list is returned.

    :param kwargs: fields names and proper value types
    :type kwargs: Any
    :return: list of returned models
    :rtype: list[Model]
    """
    if kwargs or args:
        return await self.filter(*args, **kwargs).all()

    template = self.build_select_template()
    async with self.model_config.database.get_query_executor() as executor:
        rows = await executor.fetch_all(template.statement, template.params)
    result_rows = await self._process_query_result_rows(rows)
    if self._prefetch_related and result_rows:
        result_rows = await self._prefetch_related_models(result_rows, rows)
    if self._reverse_result:
        result_rows.reverse()

    return result_rows

avg(columns) async

Returns avg value of columns for rows matching the given criteria (applied with filter and exclude if set before).

Returns:

Type Description
Union[int, float, list]

avg value of columns

Source code in ormar/queryset/queryset.py
Python
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
async def avg(self, columns: Union[str, list[str]]) -> Any:
    """
    Returns avg value of columns for rows matching the given criteria
    (applied with `filter` and `exclude` if set before).

    :return: avg value of columns
    :rtype: Union[int, float, list]
    """
    if not isinstance(columns, list):
        columns = [columns]
    return await self._query_aggr_function(func_name="avg", columns=columns)

build_select_expression(limit=None, offset=None, order_bys=None, binder=None)

Constructs the actual database query used in the QuerySet. If any of the params is not passed the QuerySet own value is used.

Parameters:

Name Type Description Default
limit Optional[int]

number to limit the query

None
offset Optional[int]

number to offset by

None
order_bys Optional[list]

list of order-by fields names

None
binder Optional[SlotBinder]

names per-call values for statement templates, if given

None

Returns:

Type Description
sqlalchemy.sql.selectable.Select

built sqlalchemy select expression

Source code in ormar/queryset/queryset.py
Python
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
def build_select_expression(
    self,
    limit: Optional[int] = None,
    offset: Optional[int] = None,
    order_bys: Optional[list] = None,
    binder: Optional[SlotBinder] = None,
) -> sqlalchemy.sql.Select:
    """
    Constructs the actual database query used in the QuerySet.
    If any of the params is not passed the QuerySet own value is used.

    :param limit: number to limit the query
    :type limit: int
    :param offset: number to offset by
    :type offset: int
    :param order_bys: list of order-by fields names
    :type order_bys: list
    :param binder: names per-call values for statement templates, if given
    :type binder: Optional[SlotBinder]
    :return: built sqlalchemy select expression
    :rtype: sqlalchemy.sql.selectable.Select
    """
    qry = Query(
        model_cls=self.model,
        select_related=self._select_related,
        filter_clauses=self.filter_clauses,
        exclude_clauses=self.exclude_clauses,
        offset=offset or self.query_offset,
        excludable=self._excludable,
        order_bys=order_bys or self.order_bys,
        limit_raw_sql=self.limit_sql_raw,
        limit_count=limit if limit is not None else self.limit_count,
        binder=binder,
    )
    exp = qry.build_select_expression()
    if self.row_lock:
        exp = exp.with_for_update(of=self.table, **self.row_lock)
    return exp

build_select_template(variant=(), limit=None, offset=None, order_bys=None, wrap=None)

Return the read statement for this queryset from the model's template cache (building and caching it on the first call of a cache key) together with the values to bind for this call::

Text Only
1
2
3
Author.objects.filter(name="a").build_select_template()
# -> StatementTemplate(statement=SELECT ... WHERE name = :ormar_p0,
#                      params={"ormar_p0": "a"})

Every read that runs a select (all, get, first, iterate, values, exists, count and the aggregates) goes through here instead of build_select_expression. A statement that is not a plain select passes wrap to build the executed statement around the select and variant to keep its cache key apart from the plain select's, e.g. count() passes variant=("count", distinct) and wrap=count_statement.

On a cache hit nothing is built: only the cache key and the values are collected from the queryset.

Parameters:

Name Type Description Default
variant tuple

how the select is used (plain, count, aggregate, ...)

()
limit Optional[int]

number to limit the query

None
offset Optional[int]

number to offset by

None
order_bys Optional[list]

list of order actions

None
wrap Optional[Callable[[Select], Any]]

turns the built select into the executed statement

None

Returns:

Type Description
StatementTemplate

statement and values to bind

Raises:

Type Description
QueryDefinitionError

if a select_for_update queryset runs outside a transaction or as count, exists or an aggregate

Source code in ormar/queryset/queryset.py
Python
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
def build_select_template(
    self,
    variant: tuple = (),
    limit: Optional[int] = None,
    offset: Optional[int] = None,
    order_bys: Optional[list] = None,
    wrap: Optional[Callable[[sqlalchemy.sql.Select], Any]] = None,
) -> StatementTemplate:
    """
    Return the read statement for this queryset from the model's template
    cache (building and caching it on the first call of a cache key) together
    with the values to bind for this call::

        Author.objects.filter(name="a").build_select_template()
        # -> StatementTemplate(statement=SELECT ... WHERE name = :ormar_p0,
        #                      params={"ormar_p0": "a"})

    Every read that runs a select (``all``, ``get``, ``first``,
    ``iterate``, ``values``, ``exists``, ``count`` and the aggregates)
    goes through here instead of ``build_select_expression``. A statement
    that is not a plain select passes ``wrap`` to build the executed
    statement around the select and ``variant`` to keep its cache key apart
    from the plain select's, e.g. ``count()`` passes
    ``variant=("count", distinct)`` and ``wrap=count_statement``.

    On a cache hit nothing is built: only the cache key and the values are
    collected from the queryset.

    :param variant: how the select is used (plain, count, aggregate, ...)
    :type variant: tuple
    :param limit: number to limit the query
    :type limit: Optional[int]
    :param offset: number to offset by
    :type offset: Optional[int]
    :param order_bys: list of order actions
    :type order_bys: Optional[list]
    :param wrap: turns the built select into the executed statement
    :type wrap: Optional[Callable[[sqlalchemy.sql.Select], Any]]
    :raises QueryDefinitionError: if a ``select_for_update`` queryset runs
        outside a transaction or as count, exists or an aggregate
    :return: statement and values to bind
    :rtype: StatementTemplate
    """
    if self.row_lock:
        if wrap is not None:
            raise QueryDefinitionError(
                "select_for_update cannot lock count, exists or aggregates, "
                "use get_or_none() / limit(1).values_list('id') instead."
            )
        if self.model_config.database.get_transaction_connection() is None:
            raise QueryDefinitionError(
                "select_for_update has to run inside a transaction."
            )
    actions = canonical_actions(
        filter_clauses=self.filter_clauses, exclude_clauses=self.exclude_clauses
    )
    params = template_params(
        actions=actions,
        limit=limit if limit is not None else self.limit_count,
        offset=offset or self.query_offset,
    )
    key = self.select_cache_key(
        variant=variant, limit=limit, offset=offset, order_bys=order_bys
    )
    cache = template_cache_for(model_cls=self.model)
    statement = cache.get(key)
    if statement is None:
        statement = self.build_template_statement(
            actions=actions,
            limit=limit,
            offset=offset,
            order_bys=order_bys,
            wrap=wrap,
        )
        cache.put(key=key, statement=statement)
    return StatementTemplate(statement=statement, params=params)

build_template_statement(actions, limit, offset, order_bys, wrap)

Build the read statement of a new cache key with named value slots, the statement that is then cached.

The select is built by build_select_expression as usual, but with a SlotBinder that turns every filter value, the limit and the offset into a named bind parameter. wrap then builds the executed statement around it, and the values of this first call are cleared from the result (see release_values).

Parameters:

Name Type Description Default
actions list

filter actions in canonical order

required
limit Optional[int]

number to limit the query

required
offset Optional[int]

number to offset by

required
order_bys Optional[list]

list of order actions

required
wrap Optional[Callable[[Select], Any]]

turns the built select into the executed statement

required

Returns:

Type Description
Any

statement to execute

Source code in ormar/queryset/queryset.py
Python
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
def build_template_statement(
    self,
    actions: list,
    limit: Optional[int],
    offset: Optional[int],
    order_bys: Optional[list],
    wrap: Optional[Callable[[sqlalchemy.sql.Select], Any]],
) -> Any:
    """
    Build the read statement of a new cache key with named value slots, the
    statement that is then cached.

    The select is built by ``build_select_expression`` as usual, but with a
    ``SlotBinder`` that turns every filter value, the limit and the offset
    into a named bind parameter. ``wrap`` then builds the executed statement
    around it, and the values of this first call are cleared from the
    result (see ``release_values``).

    :param actions: filter actions in canonical order
    :type actions: list
    :param limit: number to limit the query
    :type limit: Optional[int]
    :param offset: number to offset by
    :type offset: Optional[int]
    :param order_bys: list of order actions
    :type order_bys: Optional[list]
    :param wrap: turns the built select into the executed statement
    :type wrap: Optional[Callable[[sqlalchemy.sql.Select], Any]]
    :return: statement to execute
    :rtype: Any
    """
    binder = SlotBinder(actions=actions)
    select = self.build_select_expression(
        limit=limit, offset=offset, order_bys=order_bys, binder=binder
    )
    statement = wrap(select) if wrap is not None else select
    release_values(statement=statement)
    return statement

build_write_template(statement, values)

Return the filtered update or delete of this queryset, or a statement of update_returning() (see write_statements), from the model's template cache, with the values to bind::

Text Only
1
2
3
4
5
Author.objects.filter(score__lt=5).build_write_template(
    statement=UpdateWrite, values={"name": "x"}
)
# -> UPDATE authors SET name=:ormar_v0 WHERE authors.score < :ormar_p0
#    {"ormar_p0": 5, "ormar_v0": "x"}

The cache key is the statement class, the filter and exclude clauses (see templates.clauses_cache_key), the joined relations (filters on related models select the matched primary keys through them) and the updated column names. Updates and deletes take no ordering or limit, so nothing else changes their SQL. Filter values are named by SlotBinder like in reads, updated values like in single-row writes (ormar_v{i}).

Parameters:

Name Type Description Default
statement type[WriteStatement]

statement class

required
values dict

updated values by column name (empty for delete)

required

Returns:

Type Description
StatementTemplate

statement and values to bind

Source code in ormar/queryset/queryset.py
Python
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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
def build_write_template(
    self, statement: type[WriteStatement], values: dict
) -> StatementTemplate:
    """
    Return the filtered update or delete of this queryset, or a statement
    of ``update_returning()`` (see ``write_statements``), from the model's
    template cache, with the values to bind::

        Author.objects.filter(score__lt=5).build_write_template(
            statement=UpdateWrite, values={"name": "x"}
        )
        # -> UPDATE authors SET name=:ormar_v0 WHERE authors.score < :ormar_p0
        #    {"ormar_p0": 5, "ormar_v0": "x"}

    The cache key is the statement class, the filter and exclude clauses
    (see ``templates.clauses_cache_key``), the joined relations (filters
    on related models select the matched primary keys through them) and
    the updated column names. Updates and deletes take no ordering or
    limit, so nothing else changes their SQL. Filter values are named by
    ``SlotBinder`` like in reads, updated values like in single-row writes
    (``ormar_v{i}``).

    :param statement: statement class
    :type statement: type[WriteStatement]
    :param values: updated values by column name (empty for delete)
    :type values: dict
    :return: statement and values to bind
    :rtype: StatementTemplate
    """
    actions = canonical_actions(
        filter_clauses=self.filter_clauses, exclude_clauses=self.exclude_clauses
    )
    names = tuple(sorted(values))
    params = template_params(actions=actions, limit=None, offset=None)
    for index, name in enumerate(names):
        params.update(expression_params(value=values[name], slot=f"ormar_v{index}"))
    key = (
        statement,
        clauses_cache_key(clauses=self.filter_clauses),
        clauses_cache_key(clauses=self.exclude_clauses),
        tuple(self._select_related),
        tuple(
            (name, expression_key(node=values[name]))
            if isinstance(values[name], Expression)
            else name
            for name in names
        ),
    )
    cache = template_cache_for(model_cls=self.model)
    cached = cache.get(key)
    if cached is None:
        cached = statement.make(
            model=self.model,
            queryset=self,
            values=values,
            binder=SlotBinder(actions=actions),
        )
        release_values(statement=cached)
        cache.put(key=key, statement=cached)
    return StatementTemplate(statement=cached, params=params)

bulk_create(objects, on_conflict=None, conflict_target=None, update_fields=None, update_values=None) async

Performs a bulk create in one database session to speed up the process.

Allows you to create multiple objects at once.

A valid list of Model objects needs to be passed.

Objects that provide different sets of fields (e.g. an explicit pk or a server_default value) are inserted in separate statements, so generated primary keys may not follow the order of the passed list.

With on_conflict="ignore" rows conflicting with existing ones on any unique key are skipped. With on_conflict="update" rows conflicting on conflict_target (the primary key by default) update update_fields (by default all inserted fields but the target and the key, none when update_values are given), update_values and fields with on_update. Skipped objects are marked as saved too.

Bulk operations do not send signals.

Parameters:

Name Type Description Default
objects list[T]

list of ormar models already initialized and ready to save.

required
on_conflict Optional[Literal['ignore', 'update']]

ignore or update rows conflicting with existing ones

None
conflict_target Optional[list[str]]

names of the fields of the unique key the rows conflict on, only with update

None
update_fields Optional[list[str]]

names of the fields updated from the inserted rows, only with update

None
update_values Optional[dict[str, Any]]

values or expressions set on conflict by field name, the same for every row, only with update (see create)

None
Source code in ormar/queryset/queryset.py
Python
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
async def bulk_create(
    self,
    objects: list["T"],
    on_conflict: Optional[Literal["ignore", "update"]] = None,
    conflict_target: Optional[list[str]] = None,
    update_fields: Optional[list[str]] = None,
    update_values: Optional[dict[str, Any]] = None,
) -> None:
    """
    Performs a bulk create in one database session to speed up the process.

    Allows you to create multiple objects at once.

    A valid list of `Model` objects needs to be passed.

    Objects that provide different sets of fields (e.g. an explicit pk or a
    server_default value) are inserted in separate statements, so generated
    primary keys may not follow the order of the passed list.

    With ``on_conflict="ignore"`` rows conflicting with existing ones on any
    unique key are skipped. With ``on_conflict="update"`` rows conflicting on
    ``conflict_target`` (the primary key by default) update ``update_fields``
    (by default all inserted fields but the target and the key, none when
    ``update_values`` are given), ``update_values`` and fields with
    ``on_update``. Skipped objects are marked as saved too.

    Bulk operations do not send signals.

    :param objects: list of ormar models already initialized and ready to save.
    :type objects: list[Model]
    :param on_conflict: ``ignore`` or ``update`` rows conflicting with
        existing ones
    :type on_conflict: Optional[Literal["ignore", "update"]]
    :param conflict_target: names of the fields of the unique key the rows
        conflict on, only with ``update``
    :type conflict_target: Optional[list[str]]
    :param update_fields: names of the fields updated from the inserted
        rows, only with ``update``
    :type update_fields: Optional[list[str]]
    :param update_values: values or expressions set on conflict by field
        name, the same for every row, only with ``update`` (see ``create``)
    :type update_values: Optional[dict[str, Any]]
    """
    self.model.verify_writable()

    if not objects:
        raise ModelListEmptyError("Bulk create objects are empty!")
    if (conflict_target or update_fields or update_values) and (
        on_conflict != "update"
    ):
        raise QueryDefinitionError(
            "conflict_target, update_fields and update_values need "
            "on_conflict='update'"
        )
    on_update, conflict_values = (
        self.model._conflict_updates(
            update_fields=update_fields, update_values=update_values
        )
        if on_conflict == "update"
        else ({}, {})
    )
    # bound after the VALUES clause, the same for every row
    conflict_params = update_values_params(update_values=conflict_values)
    update_params = {
        **{
            f"ormar_on_update_{column}": value
            for column, value in on_update.items()
        },
        **conflict_params,
    }

    ready_objects = []
    trusted = self.model.flat_row_model()
    for i, obj in enumerate(objects):
        values = dump_for_save(obj=obj) if trusted else obj.model_dump()
        row = obj.prepare_model_to_save(new_kwargs=values)
        obj._verify_key_parts_set(row=row)
        ready_objects.append(row)
        if i % 100 == 99:  # pragma: no cover
            await asyncio.sleep(0)

    # rows with different key sets (explicit vs omitted pk or server_default)
    # need different inserts, so each key set runs its own insert template;
    # anything beyond a single statement (or a lone batch the driver runs
    # atomically) runs in one transaction
    rows_by_keys: dict[frozenset[str], list[dict]] = {}
    for row in ready_objects:
        rows_by_keys.setdefault(frozenset(row), []).append(row)
    database = self.model_config.database
    several_statements = len(rows_by_keys) > 1 or (
        len(ready_objects) > 1 and not database.atomic_execute_many
    )
    on_update_columns = tuple(sorted(on_update))
    # MySQL drivers turn executemany into one multi-row VALUES and leave
    # the binds after it unfilled, so a batch reads the on_update values
    # and update_values literals from user variables set once before it
    update_variables = (
        bool(update_params)
        and not database.rules.execute_many_with_trailing_binds
        and any(len(rows) > 1 for rows in rows_by_keys.values())
    )
    async with database.get_query_executor(
        transactional=several_statements
    ) as executor:
        if update_variables:  # pragma: no cover
            await executor.execute(
                query=cached_statement(
                    model_cls=self.model,
                    key=(
                        "update_assignment",
                        on_update_columns,
                        update_values_key(update_values=conflict_values),
                    ),
                    builder=build_update_assignment,
                    model=self.model,
                    on_update=on_update_columns,
                    update_values=conflict_values,
                ),
                params={
                    **{
                        f"ormar_on_update_{index}": on_update[column]
                        for index, column in enumerate(on_update_columns)
                    },
                    **conflict_params,
                },
            )
        for rows in rows_by_keys.values():
            names = tuple(sorted(rows[0]))
            # duplicates in one batch: the last wins, only while there is no
            # RETURNING (SQLAlchemy would then send a multi-row VALUES, which
            # PostgreSQL rejects for a row affected twice)
            statement = insert_statement(
                model_cls=self.model,
                names=names,
                on_conflict=on_conflict,
                conflict_target=conflict_target,
                update_fields=update_fields,
                on_update=on_update_columns,
                update_values=conflict_values,
                update_variables=update_variables,
            )
            bound_updates = {} if update_variables else update_params
            params = [
                {**value_params(names=names, values=row), **bound_updates}
                for row in rows
            ]
            if len(rows) == 1:
                await executor.execute(query=statement, params=params[0])
            else:
                await executor.execute_many(query=statement, values=params)

    for obj in objects:
        obj.set_save_status(True)

bulk_update(objects, columns=None) async

Performs bulk update in one database session to speed up the process.

Allows you to update multiple instance at once.

All Models passed need to have primary key column populated.

You can also select which fields to update by passing columns list as a list of string names.

Bulk operations do not send signals.

Parameters:

Name Type Description Default
objects list[T]

list of ormar models

required
columns Optional[list[str]]

list of columns to update

None
Source code in ormar/queryset/queryset.py
Python
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
async def bulk_update(  # noqa:  CCR001
    self, objects: list["T"], columns: Optional[list[str]] = None
) -> None:
    """
    Performs bulk update in one database session to speed up the process.

    Allows you to update multiple instance at once.

    All `Models` passed need to have primary key column populated.

    You can also select which fields to update by passing `columns` list
    as a list of string names.

    Bulk operations do not send signals.

    :param objects: list of ormar models
    :type objects: list[Model]
    :param columns: list of columns to update
    :type columns: list[str]
    """
    self.model.verify_writable()
    if not objects:
        raise ModelListEmptyError("Bulk update objects are empty!")

    ready_objects = []
    persisted_keys: list[Any] = []
    key = self.model_config.pk
    if not columns:
        columns = list(
            self.model.extract_db_own_fields().union(
                self.model.extract_related_names()
            )
        )

    for field in key.fields:
        if field not in columns:
            columns.append(field)

    onupdate_fields = self.model._onupdate_fields
    for field_name in onupdate_fields:
        if field_name not in columns:
            columns.append(field_name)

    columns = [
        alias
        for field_name in columns
        for alias in self.model.get_column_aliases(field_name=field_name)
    ]

    for i, obj in enumerate(objects):
        explicit_fields = obj.__setattr_fields__
        new_kwargs = obj.model_dump()
        if any(new_kwargs.get(field) is None for field in key.fields):
            raise ModelPersistenceError(
                "You cannot update unsaved objects. "
                f"{self.model.__name__} has to have {', '.join(key.fields)} "
                "filled."
            )
        new_kwargs = obj.populate_onupdate_value(
            new_kwargs, explicit_fields=explicit_fields
        )
        obj.update_from_dict(
            {
                field_name: new_kwargs[field_name]
                for field_name in onupdate_fields - explicit_fields
            }
        )
        new_kwargs = obj.prepare_model_to_update(new_kwargs)
        ready_objects.append(
            {"new_" + k: v for k, v in new_kwargs.items() if k in columns}
        )
        persisted_keys.append(obj.persisted_key)
        if i % 100 == 99:  # pragma: no cover
            await asyncio.sleep(0)

    pk_column_names = key.column_aliases()
    table_columns = [c.name for c in self.model_config.table.c]
    keys_moved = any(
        persisted != obj.pk for persisted, obj in zip(persisted_keys, objects)
    )
    where_prefix = "old_" if keys_moved else "new_"
    updated = tuple(
        k
        for k in columns
        if (keys_moved or k not in pk_column_names) and k in table_columns
    )
    if keys_moved:
        for row, persisted in zip(ready_objects, persisted_keys):
            parts = key.flat_parts(value=persisted)
            row.update(
                {
                    f"old_{alias}": part
                    for alias, part in zip(pk_column_names, parts)
                }
            )
    expr = cached_statement(
        model_cls=self.model,
        key=("bulk_update", updated, where_prefix),
        builder=BulkUpdateWrite.make,
        model=self.model,
        columns=updated,
        where_prefix=where_prefix,
    )
    # Multi-row execute_many: run in an explicit transaction so all rows
    # share a single COMMIT instead of one per row under AUTOCOMMIT.
    async with self.model_config.database.get_query_executor(
        transactional=True
    ) as executor:
        await executor.execute_many(expr, ready_objects)

    for obj in objects:
        obj.set_save_status(True)
        obj._reset_change_tracking()

    await cast(
        type["Model"], self.model_cls
    ).ormar_config.signals.post_bulk_update.send(
        sender=self.model_cls,  # type: ignore
        instances=objects,
    )

check_single_result_rows_count(rows) staticmethod

Verifies if the result has one and only one row.

Parameters:

Name Type Description Default
rows Sequence[Optional[T]]

one element list of Models

required
Source code in ormar/queryset/queryset.py
Python
367
368
369
370
371
372
373
374
375
376
377
378
@staticmethod
def check_single_result_rows_count(rows: Sequence[Optional["T"]]) -> None:
    """
    Verifies if the result has one and only one row.

    :param rows: one element list of Models
    :type rows: list[Model]
    """
    if not rows or rows[0] is None:
        raise NoMatch()
    if len(rows) > 1:
        raise MultipleMatches()

count(distinct=True) async

Returns number of rows matching the given criteria (applied with filter and exclude if set before). If distinct is True (the default), this will return the number of primary rows selected. If False, the count will be the total number of rows returned (including extra rows for one-to-many or many-to-many left select_related table joins). False is the legacy (buggy) behavior for workflows that depend on it.

Parameters:

Name Type Description Default
distinct bool

flag if the primary table rows should be distinct or not

True

Returns:

Type Description
int

number of rows

Source code in ormar/queryset/queryset.py
Python
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
async def count(self, distinct: bool = True) -> int:
    """
    Returns number of rows matching the given criteria
    (applied with `filter` and `exclude` if set before).
    If `distinct` is `True` (the default), this will return
    the number of primary rows selected. If `False`,
    the count will be the total number of rows returned
    (including extra rows for `one-to-many` or `many-to-many`
    left `select_related` table joins).
    `False` is the legacy (buggy) behavior for workflows that depend on it.

    :param distinct: flag if the primary table rows should be distinct or not

    :return: number of rows
    :rtype: int
    """
    wrap = functools.partial(
        count_statement,
        distinct=distinct,
        pk_column_names=self.model_config.pk.column_aliases(),
    )
    template = self.build_select_template(variant=("count", distinct), wrap=wrap)
    async with self.model_config.database.get_query_executor() as executor:
        result = await executor.fetch_val(
            query=template.statement, params=template.params
        )
        return int(result) if result is not None else 0

create(*, on_conflict=None, conflict_target=None, update_fields=None, update_values=None, **kwargs) async

Python
create(
    *, on_conflict: Literal["ignore"], **kwargs: Any
) -> Optional[T]
Python
create(
    *,
    on_conflict: Literal["update"],
    conflict_target: Optional[list[str]] = None,
    update_fields: Optional[list[str]] = None,
    update_values: Optional[dict[str, Any]] = None,
    **kwargs: Any,
) -> T
Python
create(*, on_conflict: None = None, **kwargs: Any) -> T

Creates the model instance, saves it in a database and returns the updates model (with pk populated if not passed and autoincrement is set).

The allowed kwargs are Model fields names and proper value types.

With on_conflict="ignore" a row conflicting with an existing one on any unique key is skipped and None is returned.

With on_conflict="update" a row conflicting on conflict_target (the primary key by default) is updated instead, in the same statement: update_fields (by default all passed fields but the target and the key, none when update_values are given), update_values and the fields with on_update. The stored row is returned. pre_save and post_save are sent in both cases.

Parameters:

Name Type Description Default
on_conflict Optional[Literal['ignore', 'update']]

ignore to skip a conflicting row, update to update it

None
conflict_target Optional[list[str]]

names of the fields of the unique key the row conflicts on, only with update

None
update_fields Optional[list[str]]

names of the fields updated from the inserted row, only with update

None
update_values Optional[dict[str, Any]]

values or expressions set on conflict by field name, only with update: F("x") reads the existing row, Inserted("x") the inserted one

None
kwargs Any

fields names and proper value types

{}

Returns:

Type Description
Optional[Model]

created or stored model, None when the row was skipped

Raises:

Type Description
QueryDefinitionError

for conflict_target, update_fields or update_values without on_conflict="update", a target field without a value or invalid update_values

Source code in ormar/queryset/queryset.py
Python
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
async def create(
    self,
    *,
    on_conflict: Optional[Literal["ignore", "update"]] = None,
    conflict_target: Optional[list[str]] = None,
    update_fields: Optional[list[str]] = None,
    update_values: Optional[dict[str, Any]] = None,
    **kwargs: Any,
) -> Optional["T"]:
    """
    Creates the model instance, saves it in a database and returns the updates model
    (with pk populated if not passed and autoincrement is set).

    The allowed kwargs are `Model` fields names and proper value types.

    With ``on_conflict="ignore"`` a row conflicting with an existing one on
    any unique key is skipped and ``None`` is returned.

    With ``on_conflict="update"`` a row conflicting on ``conflict_target``
    (the primary key by default) is updated instead, in the same statement:
    ``update_fields`` (by default all passed fields but the target and the
    key, none when ``update_values`` are given), ``update_values`` and the
    fields with ``on_update``. The stored row is returned. pre_save and
    post_save are sent in both cases.

    :param on_conflict: ``ignore`` to skip a conflicting row, ``update`` to
        update it
    :type on_conflict: Optional[Literal["ignore", "update"]]
    :param conflict_target: names of the fields of the unique key the row
        conflicts on, only with ``update``
    :type conflict_target: Optional[list[str]]
    :param update_fields: names of the fields updated from the inserted
        row, only with ``update``
    :type update_fields: Optional[list[str]]
    :param update_values: values or expressions set on conflict by field
        name, only with ``update``: ``F("x")`` reads the existing row,
        ``Inserted("x")`` the inserted one
    :type update_values: Optional[dict[str, Any]]
    :param kwargs: fields names and proper value types
    :type kwargs: Any
    :raises QueryDefinitionError: for ``conflict_target``,
        ``update_fields`` or ``update_values`` without
        ``on_conflict="update"``, a target field without a value or invalid
        ``update_values``
    :return: created or stored model, ``None`` when the row was skipped
    :rtype: Optional[Model]
    """
    if (conflict_target or update_fields or update_values) and (
        on_conflict != "update"
    ):
        raise QueryDefinitionError(
            "conflict_target, update_fields and update_values need "
            "on_conflict='update'"
        )
    instance = self.model(**kwargs)
    if on_conflict == "update":
        return await instance._upsert(
            conflict_target=conflict_target,
            update_fields=update_fields,
            update_values=update_values,
        )
    if on_conflict:
        return await instance._save(on_conflict=on_conflict)
    return await instance.save()

delete(*args, each=False, **kwargs) async

Deletes from the model table after applying the filters from kwargs.

You have to either pass a filter to narrow down a query or explicitly pass each=True flag to affect whole table.

Filters on related models (filter(training__instructor=instructor)) are supported, the delete removes the rows the same filters select in all() (limit and offset do not apply).

Parameters:

Name Type Description Default
each bool

flag if whole table should be affected if no filter is passed

False
kwargs Any

fields names and proper value types

{}

Returns:

Type Description
int

number of deleted rows

Source code in ormar/queryset/queryset.py
Python
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
async def delete(self, *args: Any, each: bool = False, **kwargs: Any) -> int:
    """
    Deletes from the model table after applying the filters from kwargs.

    You have to either pass a filter to narrow down a query or explicitly pass
    each=True flag to affect whole table.

    Filters on related models (``filter(training__instructor=instructor)``)
    are supported, the delete removes the rows the same filters select in
    ``all()`` (limit and offset do not apply).

    :param each: flag if whole table should be affected if no filter is passed
    :type each: bool
    :param kwargs: fields names and proper value types
    :type kwargs: Any
    :return: number of deleted rows
    :rtype: int
    """
    self.model.verify_writable()
    if kwargs or args:
        return await self.filter(*args, **kwargs).delete()
    if not each and not (self.filter_clauses or self.exclude_clauses):
        raise QueryDefinitionError(
            "You cannot delete without filtering the queryset first. "
            "If you want to delete all rows use delete(each=True)"
        )
    template = self.build_write_template(statement=DeleteWrite, values={})
    async with self.model_config.database.get_query_executor() as executor:
        return await executor.execute(template.statement, template.params)

exclude(*args, **kwargs)

Works exactly the same as filter and all modifiers (suffixes) are the same, but returns a not condition.

So if you use filter(name='John') which is where name = 'John' in SQL, the exclude(name='John') equals to where name <> 'John'

Note that all conditions are joined so if you pass multiple values it becomes a union of conditions.

exclude(name='John', age>=35) will become where not (name='John' and age>=35)

Parameters:

Name Type Description Default
kwargs Any

fields names and proper value types

{}

Returns:

Type Description
QuerySet

filtered QuerySet

Source code in ormar/queryset/queryset.py
Python
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
def exclude(self, *args: Any, **kwargs: Any) -> "QuerySet[T]":  # noqa: A003
    """
    Works exactly the same as filter and all modifiers (suffixes) are the same,
    but returns a *not* condition.

    So if you use `filter(name='John')` which is `where name = 'John'` in SQL,
    the `exclude(name='John')` equals to `where name <> 'John'`

    Note that all conditions are joined so if you pass multiple values it
    becomes a union of conditions.

    `exclude(name='John', age>=35)` will become
    `where not (name='John' and age>=35)`

    :param kwargs: fields names and proper value types
    :type kwargs: Any
    :return: filtered QuerySet
    :rtype: QuerySet
    """
    return self.filter(_exclude=True, *args, **kwargs)

exclude_fields(columns)

With exclude_fields() you can select subset of model columns that will be excluded to limit the data load.

It's the opposite of fields() method so check documentation above to see what options are available.

Especially check above how you can pass also nested dictionaries and sets as a mask to exclude fields from whole hierarchy.

Note that fields() and exclude_fields() works both for main models (on normal queries like get, all etc.) as well as select_related and prefetch_related models (with nested notation).

Mandatory fields cannot be excluded as it will raise ValidationError, to exclude a field it has to be nullable.

Pk column cannot be excluded - it's always auto added even if explicitly excluded.

Parameters:

Name Type Description Default
columns Union[list, str, set, dict]

columns to exclude

required

Returns:

Type Description
QuerySet

QuerySet

Source code in ormar/queryset/queryset.py
Python
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
def exclude_fields(self, columns: Union[list, str, set, dict]) -> "QuerySet[T]":
    """
    With `exclude_fields()` you can select subset of model columns that will
    be excluded to limit the data load.

    It's the opposite of `fields()` method so check documentation above
    to see what options are available.

    Especially check above how you can pass also nested dictionaries
    and sets as a mask to exclude fields from whole hierarchy.

    Note that `fields()` and `exclude_fields()` works both for main models
    (on normal queries like `get`, `all` etc.)
    as well as `select_related` and `prefetch_related` models
    (with nested notation).

    Mandatory fields cannot be excluded as it will raise `ValidationError`,
    to exclude a field it has to be nullable.

    Pk column cannot be excluded - it's always auto added even
    if explicitly excluded.

    :param columns: columns to exclude
    :type columns: Union[list, str, set, dict]
    :return: QuerySet
    :rtype: QuerySet
    """
    return self.fields(columns=columns, slot="exclude")

exists() async

Returns a bool value to confirm if there are rows matching the given criteria (applied with filter and exclude if set).

Returns:

Type Description
bool

result of the check

Source code in ormar/queryset/queryset.py
Python
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
async def exists(self) -> bool:
    """
    Returns a bool value to confirm if there are rows matching the given criteria
    (applied with `filter` and `exclude` if set).

    :return: result of the check
    :rtype: bool
    """
    template = self.build_select_template(
        variant=("exists",), wrap=exists_statement
    )
    async with self.model_config.database.get_query_executor() as executor:
        result = await executor.fetch_val(
            query=template.statement, params=template.params
        )
        return bool(result)

fields(columns, slot='include')

With fields() you can select subset of model columns to limit the data load.

Note that fields() and exclude_fields() works both for main models (on normal queries like get, all etc.) as well as select_related and prefetch_related models (with nested notation).

You can select specified fields by passing a str, list[str], set[str] or dict with nested definition.

To include related models use notation {related_name}__{column}[__{optional_next} etc.].

fields() can be called several times, building up the columns to select.

If you include related models into select_related() call but you won't specify columns for those models in fields - implies a list of all fields for those nested models.

Mandatory fields cannot be excluded as it will raise ValidationError, to exclude a field it has to be nullable.

Pk column cannot be excluded - it's always auto added even if not explicitly included.

You can also pass fields to include as dictionary or set.

To mark a field as included in a dictionary use it's name as key and ellipsis as value.

To traverse nested models use nested dictionaries.

To include fields at last level instead of nested dictionary a set can be used.

To include whole nested model specify model related field name and ellipsis.

Parameters:

Name Type Description Default
slot Slot

which Excludable slot to write into ("include" or "exclude")

'include'
columns Union[list, str, set, dict]

columns to include

required

Returns:

Type Description
QuerySet

QuerySet

Source code in ormar/queryset/queryset.py
Python
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
def fields(
    self, columns: Union[list, str, set, dict], slot: "Slot" = "include"
) -> "QuerySet[T]":
    """
    With `fields()` you can select subset of model columns to limit the data load.

    Note that `fields()` and `exclude_fields()` works both for main models
    (on normal queries like `get`, `all` etc.)
    as well as `select_related` and `prefetch_related`
    models (with nested notation).

    You can select specified fields by passing a `str, list[str], set[str] or
    dict` with nested definition.

    To include related models use notation
    `{related_name}__{column}[__{optional_next} etc.]`.

    `fields()` can be called several times, building up the columns to select.

    If you include related models into `select_related()` call but you won't specify
    columns for those models in fields - implies a list of all fields for
    those nested models.

    Mandatory fields cannot be excluded as it will raise `ValidationError`,
    to exclude a field it has to be nullable.

    Pk column cannot be excluded - it's always auto added even if
    not explicitly included.

    You can also pass fields to include as dictionary or set.

    To mark a field as included in a dictionary use it's name as key
    and ellipsis as value.

    To traverse nested models use nested dictionaries.

    To include fields at last level instead of nested dictionary a set can be used.

    To include whole nested model specify model related field name and ellipsis.

    :param slot: which Excludable slot to write into ("include" or "exclude")
    :type slot: Slot
    :param columns: columns to include
    :type columns: Union[list, str, set, dict]
    :return: QuerySet
    :rtype: QuerySet
    """
    excludable = ormar.ExcludableItems.from_excludable(self._excludable)
    excludable.build(
        items=columns,
        model_cls=self.model_cls,  # type: ignore
        slot=slot,
    )
    if excludable._flatten_paths:
        excludable.validate_flatten_vs_excludable(
            source_model=self.model_cls  # type: ignore
        )

    return self.rebuild_self(excludable=excludable)

filter(*args, _exclude=False, **kwargs)

Allows you to filter by any Model attribute/field as well as to fetch instances, with a filter across an FK relationship.

You can use special filter suffix to change the filter operands:

  • exact - like album__name__exact='Malibu' (exact match)
  • iexact - like album__name__iexact='malibu' (exact match case insensitive)
  • contains - like album__name__contains='Mal' (sql like)
  • icontains - like album__name__icontains='mal' (sql like case insensitive)
  • in - like album__name__in=['Malibu', 'Barclay'] (sql in)
  • isnull - like album__name__isnull=True (sql is null) (isnotnull album__name__isnull=False (sql is not null))
  • gt - like position__gt=3 (sql >)
  • gte - like position__gte=3 (sql >=)
  • lt - like position__lt=3 (sql <)
  • lte - like position__lte=3 (sql <=)
  • startswith - like album__name__startswith='Mal' (exact start match)
  • istartswith - like album__name__istartswith='mal' (case insensitive)
  • endswith - like album__name__endswith='ibu' (exact end match)
  • iendswith - like album__name__iendswith='IBU' (case insensitive)

Note that you can also use python style filters - check the docs!

Parameters:

Name Type Description Default
_exclude bool

flag if it should be exclude or filter

False
kwargs Any

fields names and proper value types

{}

Returns:

Type Description
QuerySet

filtered QuerySet

Source code in ormar/queryset/queryset.py
Python
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
def filter(  # noqa: A003
    self, *args: Any, _exclude: bool = False, **kwargs: Any
) -> "QuerySet[T]":
    """
    Allows you to filter by any `Model` attribute/field
    as well as to fetch instances, with a filter across an FK relationship.

    You can use special filter suffix to change the filter operands:

    *  exact - like `album__name__exact='Malibu'` (exact match)
    *  iexact - like `album__name__iexact='malibu'` (exact match case insensitive)
    *  contains - like `album__name__contains='Mal'` (sql like)
    *  icontains - like `album__name__icontains='mal'` (sql like case insensitive)
    *  in - like `album__name__in=['Malibu', 'Barclay']` (sql in)
    *  isnull - like `album__name__isnull=True` (sql is null)
       (isnotnull `album__name__isnull=False` (sql is not null))
    *  gt - like `position__gt=3` (sql >)
    *  gte - like `position__gte=3` (sql >=)
    *  lt - like `position__lt=3` (sql <)
    *  lte - like `position__lte=3` (sql <=)
    *  startswith - like `album__name__startswith='Mal'` (exact start match)
    *  istartswith - like `album__name__istartswith='mal'` (case insensitive)
    *  endswith - like `album__name__endswith='ibu'` (exact end match)
    *  iendswith - like `album__name__iendswith='IBU'` (case insensitive)

    Note that you can also use python style filters - check the docs!

    :param _exclude: flag if it should be exclude or filter
    :type _exclude: bool
    :param kwargs: fields names and proper value types
    :type kwargs: Any
    :return: filtered QuerySet
    :rtype: QuerySet
    """
    filter_groups, select_related = self._resolve_filter_groups(groups=args)
    qryclause = QueryClause(
        model_cls=self.model,
        select_related=select_related,
        filter_clauses=self.filter_clauses,
    )
    if _exclude:
        own_clauses, select_related = qryclause.prepare_filter(
            _own_only=True, **kwargs
        )
        if not own_clauses and not filter_groups:
            return self.rebuild_self(select_related=select_related)
        # groups are already resolved, so own actions are attached directly
        exclude_group = FilterGroup(*filter_groups)
        exclude_group.actions = own_clauses
        return self.rebuild_self(
            exclude_clauses=self.exclude_clauses + [exclude_group],
            select_related=select_related,
        )
    filter_clauses, select_related = qryclause.prepare_filter(**kwargs)
    return self.rebuild_self(
        filter_clauses=filter_clauses + filter_groups,  # type: ignore
        select_related=select_related,
    )

first(*args, **kwargs) async

Gets the first row from the db ordered by primary key column ascending.

Passing args and/or kwargs is a shortcut and equals to calling filter(*args, **kwargs).first().

The query is always executed with LIMIT 1 so at most one row is fetched; use :meth:get if you want to assert that the criteria match exactly one row.

Parameters:

Name Type Description Default
kwargs Any

fields names and proper value types

{}

Returns:

Type Description
Model

returned model

Raises:

Type Description
NoMatch

if no rows match the criteria

Source code in ormar/queryset/queryset.py
Python
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
async def first(self, *args: Any, **kwargs: Any) -> "T":
    """
    Gets the first row from the db ordered by primary key column ascending.

    Passing args and/or kwargs is a shortcut and equals to calling
    ``filter(*args, **kwargs).first()``.

    The query is always executed with ``LIMIT 1`` so at most one row is
    fetched; use :meth:`get` if you want to assert that the criteria
    match exactly one row.

    :raises NoMatch: if no rows match the criteria
    :param kwargs: fields names and proper value types
    :type kwargs: Any
    :return: returned model
    :rtype: Model
    """
    if kwargs or args:
        return await self.filter(*args, **kwargs).first()
    return await self._fetch_single(self._single_row_order_bys(reverse=False))

first_or_none(*args, **kwargs) async

Gets the first row from the db ordered by primary key column ascending.

Behaves like :meth:first but returns None instead of raising NoMatch when no row matches.

Parameters:

Name Type Description Default
kwargs Any

fields names and proper value types

{}

Returns:

Type Description
Optional[Model]

returned model or None

Source code in ormar/queryset/queryset.py
Python
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
async def first_or_none(self, *args: Any, **kwargs: Any) -> Optional["T"]:
    """
    Gets the first row from the db ordered by primary key column ascending.

    Behaves like :meth:`first` but returns ``None`` instead of raising
    ``NoMatch`` when no row matches.

    :param kwargs: fields names and proper value types
    :type kwargs: Any
    :return: returned model or None
    :rtype: Optional[Model]
    """
    try:
        return await self.first(*args, **kwargs)
    except ormar.NoMatch:
        return None

flatten_fields(columns)

Render selected related models as their primary-key value on model_dump() instead of the default nested dict.

Accepts the same input forms as :py:meth:fields / :py:meth:exclude_fields plus FieldAccessor / list of accessors. Missing relations are auto-loaded: single-valued foreign keys go into select_related, many-to-many and reverse relations into prefetch_related.

Chained calls merge. A flatten directive conflicts with any include or exclude sub-field selection on the same relation (scalar output has no place for children).

Parameters:

Name Type Description Default
columns Union[list, str, set, tuple, dict, FieldAccessor]

relations to flatten on serialization

required

Returns:

Type Description
QuerySet[T]

new QuerySet with the flatten spec applied

Source code in ormar/queryset/queryset.py
Python
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
def flatten_fields(
    self,
    columns: Union[list, str, set, tuple, dict, FieldAccessor],
) -> "QuerySet[T]":
    """
    Render selected related models as their primary-key value on
    ``model_dump()`` instead of the default nested dict.

    Accepts the same input forms as :py:meth:`fields` / :py:meth:`exclude_fields`
    plus ``FieldAccessor`` / list of accessors. Missing relations are
    auto-loaded: single-valued foreign keys go into ``select_related``,
    many-to-many and reverse relations into ``prefetch_related``.

    Chained calls merge. A flatten directive conflicts with any include or
    exclude sub-field selection on the same relation (scalar output has no
    place for children).

    :param columns: relations to flatten on serialization
    :type columns: Union[list, str, set, tuple, dict, FieldAccessor]
    :return: new QuerySet with the flatten spec applied
    :rtype: QuerySet[T]
    """
    normalized = extract_access_chains(columns)

    excludable = ormar.ExcludableItems.from_excludable(self._excludable)
    excludable.build(
        items=normalized,
        model_cls=self.model_cls,  # type: ignore
        slot="flatten",
    )
    excludable.validate_flatten_vs_excludable(
        source_model=self.model_cls  # type: ignore
    )

    select_to_add, prefetch_to_add = self._classify_flatten_paths(
        excludable._flatten_paths
    )
    new_select = sorted(set(self._select_related) | select_to_add)
    new_prefetch = sorted(set(self._prefetch_related) | prefetch_to_add)
    return self.rebuild_self(
        excludable=excludable,
        select_related=new_select,
        prefetch_related=new_prefetch,
    )

get(*args, **kwargs) async

Gets a single row from the db matching the criteria set by args/kwargs.

Passing args/kwargs is a shortcut for filter(*args, **kwargs).get().

When criteria are set (either through args/kwargs here or via a chained :meth:filter/:meth:exclude) the query fetches every matching row and asserts that exactly one comes back — NoMatch is raised when none match and MultipleMatches when more than one matches.

When no criteria are set, get() falls back to returning the last row of the table ordered by primary key descending (LIMIT 1); in that mode MultipleMatches cannot be raised.

Parameters:

Name Type Description Default
kwargs Any

fields names and proper value types

{}

Returns:

Type Description
Model

returned model

Raises:

Type Description
NoMatch

if no rows match the criteria

MultipleMatches

when criteria are set and more than one row matches them.

Source code in ormar/queryset/queryset.py
Python
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
async def get(self, *args: Any, **kwargs: Any) -> "T":  # noqa: CCR001
    """
    Gets a single row from the db matching the criteria set by args/kwargs.

    Passing args/kwargs is a shortcut for ``filter(*args, **kwargs).get()``.

    When criteria are set (either through args/kwargs here or via a
    chained :meth:`filter`/:meth:`exclude`) the query fetches every
    matching row and asserts that exactly one comes back — ``NoMatch``
    is raised when none match and ``MultipleMatches`` when more than one
    matches.

    When no criteria are set, ``get()`` falls back to returning the last
    row of the table ordered by primary key descending (``LIMIT 1``); in
    that mode ``MultipleMatches`` cannot be raised.

    :raises NoMatch: if no rows match the criteria
    :raises MultipleMatches: when criteria are set and more than one row
        matches them.
    :param kwargs: fields names and proper value types
    :type kwargs: Any
    :return: returned model
    :rtype: Model
    """
    if kwargs or args:
        return await self.filter(*args, **kwargs).get()

    if not (self.filter_clauses or self.exclude_clauses):
        template = self.build_select_template(
            limit=1,
            order_bys=(
                [
                    OrderAction(
                        order_str=f"-{field}",
                        model_cls=self.model_cls,  # type: ignore
                    )
                    for field in self.model_config.pk.fields
                ]
                if not any([x.is_source_model_order for x in self.order_bys])
                else []
            )
            + self.order_bys,
        )
    else:
        template = self.build_select_template()

    async with self.model_config.database.get_query_executor() as executor:
        rows = await executor.fetch_all(template.statement, template.params)
    processed_rows = await self._process_query_result_rows(rows)
    if self._prefetch_related and processed_rows:
        processed_rows = await self._prefetch_related_models(processed_rows, rows)
    self.check_single_result_rows_count(processed_rows)
    return processed_rows[0]  # type: ignore

get_or_create(_defaults=None, *args, **kwargs) async

Combination of create and get methods.

Tries to get a row meeting the criteria for kwargs and if NoMatch exception is raised it creates a new one with given kwargs and _defaults.

If a concurrent caller wins the race and creates a matching row between this call's get and create, the create raises sqlalchemy.exc.IntegrityError and get is retried once. If the retry still finds no row, the original IntegrityError is re-raised because the violation isn't a race but a legitimate constraint conflict (e.g. a different unique key). Inside a transaction the create runs in a savepoint, so the transaction stays usable.

Passing a criteria is actually calling filter(args, *kwargs) method described below.

Parameters:

Name Type Description Default
kwargs Any

fields names and proper value types

{}
_defaults Optional[dict[str, Any]]

default values for creating object

None

Returns:

Type Description
tuple("T", bool)

model instance and a boolean

Source code in ormar/queryset/queryset.py
Python
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
async def get_or_create(
    self,
    _defaults: Optional[dict[str, Any]] = None,
    *args: Any,
    **kwargs: Any,
) -> tuple["T", bool]:
    """
    Combination of create and get methods.

    Tries to get a row meeting the criteria for kwargs
    and if `NoMatch` exception is raised
    it creates a new one with given kwargs and _defaults.

    If a concurrent caller wins the race and creates a matching row
    between this call's ``get`` and ``create``, the ``create`` raises
    ``sqlalchemy.exc.IntegrityError`` and ``get`` is retried once.
    If the retry still finds no row, the original ``IntegrityError`` is
    re-raised because the violation isn't a race but a legitimate
    constraint conflict (e.g. a different unique key). Inside a transaction
    the ``create`` runs in a savepoint, so the transaction stays usable.

    Passing a criteria is actually calling filter(*args, **kwargs) method described
    below.

    :param kwargs: fields names and proper value types
    :type kwargs: Any
    :param _defaults: default values for creating object
    :type _defaults: Optional[dict[str, Any]]
    :return: model instance and a boolean
    :rtype: tuple("T", bool)
    """
    _defaults = _defaults or {}
    return await get_or_create_with_retry(
        database=self.model_config.database,
        get=lambda: self.get(*args, **kwargs),
        create=lambda: self.create(**{**kwargs, **_defaults}),
    )

get_or_none(*args, **kwargs) async

Gets a single row from the db matching the criteria set by args/kwargs.

Behaves like :meth:get but returns None instead of raising NoMatch when no row matches. MultipleMatches is still raised when criteria are provided and more than one row matches.

Parameters:

Name Type Description Default
kwargs Any

fields names and proper value types

{}

Returns:

Type Description
Optional[Model]

returned model or None

Raises:

Type Description
MultipleMatches

when criteria are set (via filter/exclude or args/kwargs) and more than one row matches them.

Source code in ormar/queryset/queryset.py
Python
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
async def get_or_none(self, *args: Any, **kwargs: Any) -> Optional["T"]:
    """
    Gets a single row from the db matching the criteria set by args/kwargs.

    Behaves like :meth:`get` but returns ``None`` instead of raising
    ``NoMatch`` when no row matches. ``MultipleMatches`` is still raised
    when criteria are provided and more than one row matches.

    :raises MultipleMatches: when criteria are set (via ``filter``/``exclude``
        or args/kwargs) and more than one row matches them.
    :param kwargs: fields names and proper value types
    :type kwargs: Any
    :return: returned model or None
    :rtype: Optional[Model]
    """
    try:
        return await self.get(*args, **kwargs)
    except ormar.NoMatch:
        return None

iterate(*args, **kwargs) async

Return async iterable generator for all rows from a database for given model.

Passing args and/or kwargs is a shortcut and equals to calling filter(*args, **kwargs).iterate().

If there are no rows meeting the criteria an empty async generator is returned.

Parameters:

Name Type Description Default
kwargs Any

fields names and proper value types

{}

Returns:

Type Description
AsyncGenerator[Model]

asynchronous iterable generator of returned models

Source code in ormar/queryset/queryset.py
Python
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
async def iterate(  # noqa: A003
    self,
    *args: Any,
    **kwargs: Any,
) -> AsyncGenerator["T", None]:
    """
    Return async iterable generator for all rows from a database for given model.

    Passing args and/or kwargs is a shortcut and equals to calling
    `filter(*args, **kwargs).iterate()`.

    If there are no rows meeting the criteria an empty async generator is returned.

    :param kwargs: fields names and proper value types
    :type kwargs: Any
    :return: asynchronous iterable generator of returned models
    :rtype: AsyncGenerator[Model]
    """

    if self._prefetch_related:
        raise QueryDefinitionError(
            "Prefetch related queries are not supported in iterators"
        )

    if kwargs or args:
        async for result in self.filter(*args, **kwargs).iterate():
            yield result
        return

    template = self.build_select_template()

    rows: list = []
    last_primary_key = None
    read_pk = self.model_config.pk.getter(
        keys=self.model_config.pk.column_aliases()
    )
    # Single shared cache across all yielded chunks so 1-row chunks
    # (the common iterate case) still amortize the plan build.
    plan_cache: dict = {}

    # Server-side cursor (asyncpg/aiomysql) requires an open transaction,
    # which AUTOCOMMIT does not provide.
    async with self.model_config.database.get_query_executor(
        transactional=True
    ) as executor:
        async for row in executor.iterate(template.statement, template.params):
            current_primary_key = read_pk(row)
            if last_primary_key == current_primary_key or last_primary_key is None:
                last_primary_key = current_primary_key
                rows.append(row)
                continue

            yield (await self._process_query_result_rows(rows, plan_cache))[0]
            last_primary_key = current_primary_key
            rows = [row]

        if rows:
            yield (await self._process_query_result_rows(rows, plan_cache))[0]

last(*args, **kwargs) async

Gets the last row from the db ordered by primary key column descending.

Complementary to :meth:first: the default pk ordering is flipped and the top row is returned. Passing args and/or kwargs is a shortcut and equals to calling filter(*args, **kwargs).last().

The query is always executed with LIMIT 1 so at most one row is fetched; use :meth:get if you want to assert that the criteria match exactly one row.

Parameters:

Name Type Description Default
kwargs Any

fields names and proper value types

{}

Returns:

Type Description
Model

returned model

Raises:

Type Description
NoMatch

if no rows match the criteria

Source code in ormar/queryset/queryset.py
Python
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
async def last(self, *args: Any, **kwargs: Any) -> "T":
    """
    Gets the last row from the db ordered by primary key column descending.

    Complementary to :meth:`first`: the default pk ordering is flipped
    and the top row is returned. Passing args and/or kwargs is a shortcut
    and equals to calling ``filter(*args, **kwargs).last()``.

    The query is always executed with ``LIMIT 1`` so at most one row is
    fetched; use :meth:`get` if you want to assert that the criteria
    match exactly one row.

    :raises NoMatch: if no rows match the criteria
    :param kwargs: fields names and proper value types
    :type kwargs: Any
    :return: returned model
    :rtype: Model
    """
    if kwargs or args:
        return await self.filter(*args, **kwargs).last()
    return await self._fetch_single(self._single_row_order_bys(reverse=True))

last_or_none(*args, **kwargs) async

Gets the last row from the db ordered by primary key column descending.

Behaves like :meth:last but returns None instead of raising NoMatch when no row matches.

Parameters:

Name Type Description Default
kwargs Any

fields names and proper value types

{}

Returns:

Type Description
Optional[Model]

returned model or None

Source code in ormar/queryset/queryset.py
Python
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
async def last_or_none(self, *args: Any, **kwargs: Any) -> Optional["T"]:
    """
    Gets the last row from the db ordered by primary key column descending.

    Behaves like :meth:`last` but returns ``None`` instead of raising
    ``NoMatch`` when no row matches.

    :param kwargs: fields names and proper value types
    :type kwargs: Any
    :return: returned model or None
    :rtype: Optional[Model]
    """
    try:
        return await self.last(*args, **kwargs)
    except ormar.NoMatch:
        return None

limit(limit_count, limit_raw_sql=None)

You can limit the results to desired number of parent models.

To limit the actual number of database query rows instead of number of main models use the limit_raw_sql parameter flag, and set it to True.

Parameters:

Name Type Description Default
limit_raw_sql Optional[bool]

flag if raw sql should be limited

None
limit_count int

number of models to limit

required

Returns:

Type Description
QuerySet

QuerySet

Source code in ormar/queryset/queryset.py
Python
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
def limit(
    self, limit_count: int, limit_raw_sql: Optional[bool] = None
) -> "QuerySet[T]":
    """
    You can limit the results to desired number of parent models.

    To limit the actual number of database query rows instead of number of main
    models use the `limit_raw_sql` parameter flag, and set it to `True`.

    :param limit_raw_sql: flag if raw sql should be limited
    :type limit_raw_sql: bool
    :param limit_count: number of models to limit
    :type limit_count: int
    :return: QuerySet
    :rtype: QuerySet
    """
    limit_raw_sql = self.limit_sql_raw if limit_raw_sql is None else limit_raw_sql
    return self.rebuild_self(limit_count=limit_count, limit_raw_sql=limit_raw_sql)

limit_cache_key(limit)

Return how the effective limit changes the SQL: whether a LIMIT is applied at all, and whether it is non-zero (only a non-zero limit with select_related builds the pagination subquery). The limit value itself is bound, so limit(5) and limit(10) share a statement::

Text Only
1
2
3
limit(None) -> (False, False)
limit(0)    -> (True, False)
limit(10)   -> (True, True)

Parameters:

Name Type Description Default
limit Optional[int]

limit passed to build_select_expression

required

Returns:

Type Description
tuple

limit presence and truthiness

Source code in ormar/queryset/queryset.py
Python
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
def limit_cache_key(self, limit: Optional[int]) -> tuple:
    """
    Return how the effective limit changes the SQL: whether a LIMIT is
    applied at all, and whether it is non-zero (only a non-zero limit with
    ``select_related`` builds the pagination subquery). The limit value
    itself is bound, so ``limit(5)`` and ``limit(10)`` share a statement::

        limit(None) -> (False, False)
        limit(0)    -> (True, False)
        limit(10)   -> (True, True)

    :param limit: limit passed to ``build_select_expression``
    :type limit: Optional[int]
    :return: limit presence and truthiness
    :rtype: tuple
    """
    effective = limit if limit is not None else self.limit_count
    return effective is not None, bool(effective)

matched_rows_clause(binder)

Return the condition keeping the rows this queryset selects, by primary key, for an update or delete filtering on related models::

Text Only
1
2
3
4
tracks.id IN (SELECT ormar_matched.id FROM (
    SELECT tracks.id FROM tracks LEFT OUTER JOIN albums AS ... ON ...
    WHERE <filters>
) AS ormar_matched)

The select is wrapped in a derived table, as MySQL does not let a statement select from the table it updates or deletes from (error 1093). A composite primary key is compared as a tuple.

Parameters:

Name Type Description Default
binder Optional[SlotBinder]

names filter values for templates, None binds them as plain values

required

Returns:

Type Description
Any

condition on the primary key columns

Source code in ormar/queryset/queryset.py
Python
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
def matched_rows_clause(self, binder: Optional[SlotBinder]) -> Any:
    """
    Return the condition keeping the rows this queryset selects, by primary
    key, for an update or delete filtering on related models::

        tracks.id IN (SELECT ormar_matched.id FROM (
            SELECT tracks.id FROM tracks LEFT OUTER JOIN albums AS ... ON ...
            WHERE <filters>
        ) AS ormar_matched)

    The select is wrapped in a derived table, as MySQL does not let a
    statement select from the table it updates or deletes from (error
    1093). A composite primary key is compared as a tuple.

    :param binder: names filter values for templates, None binds them as
        plain values
    :type binder: Optional[SlotBinder]
    :return: condition on the primary key columns
    :rtype: Any
    """
    matched = (
        Query(
            model_cls=self.model,
            filter_clauses=self.filter_clauses,
            exclude_clauses=self.exclude_clauses,
            select_related=self._select_related,
            limit_count=None,
            offset=None,
            excludable=self._excludable,
            order_bys=None,
            limit_raw_sql=False,
            binder=binder,
        )
        .build_primary_key_select()
        .subquery("ormar_matched")
    )
    return self.model_config.pk.row_value().in_(sqlalchemy.select(*matched.c))

max(columns) async

Returns max value of columns for rows matching the given criteria (applied with filter and exclude if set before).

Returns:

Type Description
Any

max value of column(s)

Source code in ormar/queryset/queryset.py
Python
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
async def max(self, columns: Union[str, list[str]]) -> Any:  # noqa: A003
    """
    Returns max value of columns for rows matching the given criteria
    (applied with `filter` and `exclude` if set before).

    :return: max value of column(s)
    :rtype: Any
    """
    if not isinstance(columns, list):
        columns = [columns]
    return await self._query_aggr_function(func_name="max", columns=columns)

min(columns) async

Returns min value of columns for rows matching the given criteria (applied with filter and exclude if set before).

Returns:

Type Description
Any

min value of column(s)

Source code in ormar/queryset/queryset.py
Python
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
async def min(self, columns: Union[str, list[str]]) -> Any:  # noqa: A003
    """
    Returns min value of columns for rows matching the given criteria
    (applied with `filter` and `exclude` if set before).

    :return: min value of column(s)
    :rtype: Any
    """
    if not isinstance(columns, list):
        columns = [columns]
    return await self._query_aggr_function(func_name="min", columns=columns)

offset(offset, limit_raw_sql=None)

You can also offset the results by desired number of main models.

To offset the actual number of database query rows instead of number of main models use the limit_raw_sql parameter flag, and set it to True.

Parameters:

Name Type Description Default
limit_raw_sql Optional[bool]

flag if raw sql should be offset

None
offset int

numbers of models to offset

required

Returns:

Type Description
QuerySet

QuerySet

Source code in ormar/queryset/queryset.py
Python
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
def offset(
    self, offset: int, limit_raw_sql: Optional[bool] = None
) -> "QuerySet[T]":
    """
    You can also offset the results by desired number of main models.

    To offset the actual number of database query rows instead of number of main
    models use the `limit_raw_sql` parameter flag, and set it to `True`.

    :param limit_raw_sql: flag if raw sql should be offset
    :type limit_raw_sql: bool
    :param offset: numbers of models to offset
    :type offset: int
    :return: QuerySet
    :rtype: QuerySet
    """
    limit_raw_sql = self.limit_sql_raw if limit_raw_sql is None else limit_raw_sql
    return self.rebuild_self(offset=offset, limit_raw_sql=limit_raw_sql)

order_by(columns)

With order_by() you can order the results from database based on your choice of fields.

You can provide a string with field name or list of strings with fields names.

Ordering in sql will be applied in order of names you provide in order_by.

By default if you do not provide ordering ormar explicitly orders by all primary keys

If you are sorting by nested models that causes that the result rows are unsorted by the main model ormar will combine those children rows into one main model.

The main model will never duplicate in the result

To order by main model field just provide a field name

To sort on nested models separate field names with dunder '__'.

You can sort this way across all relation types -> ForeignKey, reverse virtual FK and ManyToMany fields.

To sort in descending order provide a hyphen in front of the field name

To sort randomly provide "?", ormar.random() or ormar.Random()

Parameters:

Name Type Description Default
columns Union[list, str, OrderAction, RandomOrder, Random]

columns by which models should be sorted

required

Returns:

Type Description
QuerySet

QuerySet

Source code in ormar/queryset/queryset.py
Python
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
def order_by(
    self, columns: Union[list, str, OrderAction, RandomOrder, Random]
) -> "QuerySet[T]":
    """
    With `order_by()` you can order the results from database based on your
    choice of fields.

    You can provide a string with field name or list of strings with fields names.

    Ordering in sql will be applied in order of names you provide in order_by.

    By default if you do not provide ordering `ormar` explicitly orders by
    all primary keys

    If you are sorting by nested models that causes that the result rows are
    unsorted by the main model `ormar` will combine those children rows into
    one main model.

    The main model will never duplicate in the result

    To order by main model field just provide a field name

    To sort on nested models separate field names with dunder '__'.

    You can sort this way across all relation types -> `ForeignKey`,
    reverse virtual FK and `ManyToMany` fields.

    To sort in descending order provide a hyphen in front of the field name

    To sort randomly provide ``"?"``, ``ormar.random()`` or ``ormar.Random()``

    :param columns: columns by which models should be sorted
    :type columns: Union[list, str]
    :return: QuerySet
    :rtype: QuerySet
    """
    if not isinstance(columns, list):
        columns = [columns]
    orders_by = expand_pk_orders(model_cls=self.model, columns=columns)

    order_bys = self.order_bys + [x for x in orders_by if x not in self.order_bys]
    return self.rebuild_self(order_bys=order_bys)

paginate(page, page_size=20)

You can paginate the result which is a combination of offset and limit clauses. Limit is set to page size and offset is set to (page-1) * page_size.

Parameters:

Name Type Description Default
page_size int

numbers of items per page

20
page int

page number

required

Returns:

Type Description
QuerySet

QuerySet

Source code in ormar/queryset/queryset.py
Python
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
def paginate(self, page: int, page_size: int = 20) -> "QuerySet[T]":
    """
    You can paginate the result which is a combination of offset and limit clauses.
    Limit is set to page size and offset is set to (page-1) * page_size.

    :param page_size: numbers of items per page
    :type page_size: int
    :param page: page number
    :type page: int
    :return: QuerySet
    :rtype: QuerySet
    """
    if page < 1 or page_size < 1:
        raise QueryDefinitionError("Page size and page have to be greater than 0.")

    limit_count = page_size
    query_offset = (page - 1) * page_size
    return self.rebuild_self(limit_count=limit_count, offset=query_offset)

Allows to prefetch related models during query - but opposite to select_related each subsequent model is fetched in a separate database query.

With prefetch_related always one query per Model is run against the database, meaning that you will have multiple queries executed one after another.

To fetch related model use ForeignKey names.

To chain related Models relation use double underscores between names.

Parameters:

Name Type Description Default
related Union[list, str, FieldAccessor, Prefetch]

list of relation field names, can be linked by '__' to nest

required

Returns:

Type Description
QuerySet

QuerySet

Source code in ormar/queryset/queryset.py
Python
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
def prefetch_related(
    self, related: Union[list, str, FieldAccessor, Prefetch]
) -> "QuerySet[T]":
    """
    Allows to prefetch related models during query - but opposite to
    `select_related` each subsequent model is fetched in a separate database query.

    **With `prefetch_related` always one query per Model is run against the
    database**, meaning that you will have multiple queries executed one
    after another.

    To fetch related model use `ForeignKey` names.

    To chain related `Models` relation use double underscores between names.

    :param related: list of relation field names, can be linked by '__' to nest
    :type related: Union[list, str]
    :return: QuerySet
    :rtype: QuerySet
    """
    if not isinstance(related, list):
        related = [related]
    querysets = dict(self._prefetch_querysets)
    for item in related:
        if isinstance(item, Prefetch):
            if not isinstance(item.queryset, QuerySet):
                raise QueryDefinitionError(
                    f"Prefetch queryset must be a QuerySet, got {item.queryset!r}."
                )
            (path,) = extract_access_chains([item.relation])
            querysets[path] = item.queryset
    related = [
        item.relation if isinstance(item, Prefetch) else item for item in related
    ]
    related = cast(list, extract_access_chains(related))

    related = list(set(list(self._prefetch_related) + related))
    return self.rebuild_self(prefetch_related=related, prefetch_querysets=querysets)

rebuild_self(filter_clauses=None, exclude_clauses=None, select_related=None, limit_count=None, offset=None, excludable=None, order_bys=None, prefetch_related=None, limit_raw_sql=None, proxy_source_model=None, reverse_result=None, prefetch_querysets=None, row_lock=None)

Method that returns new instance of queryset based on passed params, all not passed params are taken from current values.

Source code in ormar/queryset/queryset.py
Python
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
def rebuild_self(  # noqa: CFQ002
    self,
    filter_clauses: Optional[list] = None,
    exclude_clauses: Optional[list] = None,
    select_related: Optional[list] = None,
    limit_count: Optional[int] = None,
    offset: Optional[int] = None,
    excludable: Optional["ExcludableItems"] = None,
    order_bys: Optional[list] = None,
    prefetch_related: Optional[list] = None,
    limit_raw_sql: Optional[bool] = None,
    proxy_source_model: Optional[type["Model"]] = None,
    reverse_result: Optional[bool] = None,
    prefetch_querysets: Optional[dict[str, "QuerySet"]] = None,
    row_lock: Optional[dict[str, bool]] = None,
) -> "QuerySet":
    """
    Method that returns new instance of queryset based on passed params,
    all not passed params are taken from current values.
    """
    overwrites = {
        "select_related": "_select_related",
        "offset": "query_offset",
        "excludable": "_excludable",
        "prefetch_related": "_prefetch_related",
        "limit_raw_sql": "limit_sql_raw",
        "reverse_result": "_reverse_result",
        "prefetch_querysets": "_prefetch_querysets",
    }
    passed_args = locals()

    def replace_if_none(arg_name: str) -> Any:
        if passed_args.get(arg_name) is None:
            return getattr(self, overwrites.get(arg_name, arg_name))
        return passed_args.get(arg_name)

    return self.__class__(
        model_cls=self.model_cls,
        filter_clauses=replace_if_none("filter_clauses"),
        exclude_clauses=replace_if_none("exclude_clauses"),
        select_related=replace_if_none("select_related"),
        limit_count=replace_if_none("limit_count"),
        offset=replace_if_none("offset"),
        excludable=replace_if_none("excludable"),
        order_bys=replace_if_none("order_bys"),
        prefetch_related=replace_if_none("prefetch_related"),
        limit_raw_sql=replace_if_none("limit_raw_sql"),
        proxy_source_model=replace_if_none("proxy_source_model"),
        reverse_result=replace_if_none("reverse_result"),
        prefetch_querysets=replace_if_none("prefetch_querysets"),
        row_lock=replace_if_none("row_lock"),
    )

select_all(follow=False, max_depth=None, follow_reverse=0)

By default adds only directly related models.

If follow=True is set it adds also related models of related models.

To not get stuck in an infinite loop as related models also keep a relation to parent model visited models set is kept.

That way already visited models that are nested are loaded, but the load do not follow them inside. So Model A -> Model B -> Model C -> Model A -> Model X will load second Model A but will never follow into Model X. Nested relations of those kind need to be loaded manually.

Parameters:

Name Type Description Default
follow bool

flag to trigger deep save - by default only directly related models are saved with follow=True also related models of related models are saved

False
max_depth Optional[int]

number of relations to follow at most with follow=True, forward foreign keys DEFAULT_FOLLOW_DEPTH (5) deep by default (every relation without limit in the deprecated map traversal)

None
follow_reverse Union[bool, int]

number of first levels where follow=True also follows reverse and many to many relations, True = 1

0

Returns:

Type Description
Model

reloaded Model

Source code in ormar/queryset/queryset.py
Python
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
def select_all(
    self,
    follow: bool = False,
    max_depth: Optional[int] = None,
    follow_reverse: Union[bool, int] = 0,
) -> "QuerySet[T]":
    """
    By default adds only directly related models.

    If follow=True is set it adds also related models of related models.

    To not get stuck in an infinite loop as related models also keep a relation
    to parent model visited models set is kept.

    That way already visited models that are nested are loaded, but the load do not
    follow them inside. So Model A -> Model B -> Model C -> Model A -> Model X
    will load second Model A but will never follow into Model X.
    Nested relations of those kind need to be loaded manually.

    :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 max_depth: number of relations to follow at most with
        follow=True, forward foreign keys ``DEFAULT_FOLLOW_DEPTH`` (5) deep by
        default (every relation without limit in the deprecated ``map``
        traversal)
    :type max_depth: Optional[int]
    :param follow_reverse: number of first levels where follow=True also
        follows reverse and many to many relations, ``True`` = 1
    :type follow_reverse: Union[bool, int]
    :return: reloaded Model
    :rtype: Model
    """
    relations = list(self.model.extract_related_names())
    if follow:
        relations = self.model._follow_relation_paths(
            max_depth=max_depth, follow_reverse=follow_reverse
        )
    return self.rebuild_self(select_related=relations)

select_cache_key(variant, limit, offset, order_bys)

Return the cache key of the statement build_select_expression would build with the given arguments: everything that changes its SQL text and none of the bound values. Two querysets with the same key must build the same SQL, or one would run the other's statement, so each part covers one input of the build:

  • variant - plain select, exists, count or aggregate
  • filter and exclude clauses - see clauses_cache_key
  • select_related - the joins
  • selected fields - see excludable_cache_key
  • ordering - see order_cache_key
  • limit and offset presence - see limit_cache_key
  • limit_raw_sql - limit on raw rows instead of main models
  • row_lock - the select_for_update options

Any new queryset option that changes the built SQL has to be added here; the cross check of the test suite fails when one is missing.

Parameters:

Name Type Description Default
variant tuple

how the select is used (plain, count, aggregate, ...)

required
limit Optional[int]

limit passed to build_select_expression

required
offset Optional[int]

offset passed to build_select_expression

required
order_bys Optional[list]

order actions passed to build_select_expression

required

Returns:

Type Description
tuple

hashable cache key of the statement

Source code in ormar/queryset/queryset.py
Python
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
def select_cache_key(
    self,
    variant: tuple,
    limit: Optional[int],
    offset: Optional[int],
    order_bys: Optional[list],
) -> tuple:
    """
    Return the cache key of the statement ``build_select_expression`` would build
    with the given arguments: everything that changes its SQL text and none
    of the bound values. Two querysets with the same key must build the
    same SQL, or one would run the other's statement, so each part covers
    one input of the build:

    * ``variant`` - plain select, exists, count or aggregate
    * filter and exclude clauses - see ``clauses_cache_key``
    * ``select_related`` - the joins
    * selected fields - see ``excludable_cache_key``
    * ordering - see ``order_cache_key``
    * limit and offset presence - see ``limit_cache_key``
    * ``limit_raw_sql`` - limit on raw rows instead of main models
    * ``row_lock`` - the ``select_for_update`` options

    Any new queryset option that changes the built SQL has to be added
    here; the cross check of the test suite fails when one is missing.

    :param variant: how the select is used (plain, count, aggregate, ...)
    :type variant: tuple
    :param limit: limit passed to ``build_select_expression``
    :type limit: Optional[int]
    :param offset: offset passed to ``build_select_expression``
    :type offset: Optional[int]
    :param order_bys: order actions passed to ``build_select_expression``
    :type order_bys: Optional[list]
    :return: hashable cache key of the statement
    :rtype: tuple
    """
    return (
        variant,
        clauses_cache_key(clauses=self.filter_clauses),
        clauses_cache_key(clauses=self.exclude_clauses),
        tuple(self._select_related),
        excludable_cache_key(excludable=self._excludable),
        order_cache_key(order_bys=order_bys or self.order_bys),
        self.limit_cache_key(limit=limit),
        bool(offset or self.query_offset),
        self.limit_sql_raw,
        tuple(self.row_lock.items()),
    )

select_for_update(nowait=False, skip_locked=False, read=False, no_key=False)

Lock the rows of the main model read by this queryset until the end of the transaction (SELECT ... FOR UPDATE OF <table>). It has to run inside a transaction; joined related models are not locked and SQLite runs the query without locks.

Parameters:

Name Type Description Default
nowait bool

raise instead of waiting for rows locked by others

False
skip_locked bool

skip rows locked by others instead of waiting

False
read bool

take a shared lock (FOR SHARE)

False
no_key bool

weaker PostgreSQL lock that does not block inserts of rows referencing the locked ones (FOR NO KEY UPDATE / FOR KEY SHARE)

False

Returns:

Type Description
QuerySet

QuerySet

Raises:

Type Description
QueryDefinitionError

if both nowait and skip_locked are set

Source code in ormar/queryset/queryset.py
Python
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
def select_for_update(
    self,
    nowait: bool = False,
    skip_locked: bool = False,
    read: bool = False,
    no_key: bool = False,
) -> "QuerySet[T]":
    """
    Lock the rows of the main model read by this queryset until the end of
    the transaction (``SELECT ... FOR UPDATE OF <table>``). It has to run
    inside a transaction; joined related models are not locked and SQLite
    runs the query without locks.

    :param nowait: raise instead of waiting for rows locked by others
    :type nowait: bool
    :param skip_locked: skip rows locked by others instead of waiting
    :type skip_locked: bool
    :param read: take a shared lock (``FOR SHARE``)
    :type read: bool
    :param no_key: weaker PostgreSQL lock that does not block inserts of
        rows referencing the locked ones (``FOR NO KEY UPDATE`` /
        ``FOR KEY SHARE``)
    :type no_key: bool
    :raises QueryDefinitionError: if both nowait and skip_locked are set
    :return: QuerySet
    :rtype: QuerySet
    """
    if nowait and skip_locked:
        raise QueryDefinitionError("Use either nowait or skip_locked, not both.")
    return self.rebuild_self(
        row_lock={
            "nowait": nowait,
            "skip_locked": skip_locked,
            "read": read,
            "key_share": no_key,
        }
    )

Allows to prefetch related models during the same query.

With select_related always only one query is run against the database, meaning that one (sometimes complicated) join is generated and later nested models are processed in python.

To fetch related model use ForeignKey names.

To chain related Models relation use double underscores between names.

Parameters:

Name Type Description Default
related Union[list, str, FieldAccessor]

list of relation field names, can be linked by '__' to nest

required

Returns:

Type Description
QuerySet

QuerySet

Source code in ormar/queryset/queryset.py
Python
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
def select_related(self, related: Union[list, str, FieldAccessor]) -> "QuerySet[T]":
    """
    Allows to prefetch related models during the same query.

    **With `select_related` always only one query is run against the database**,
    meaning that one (sometimes complicated) join is generated and later nested
    models are processed in python.

    To fetch related model use `ForeignKey` names.

    To chain related `Models` relation use double underscores between names.

    :param related: list of relation field names, can be linked by '__' to nest
    :type related: Union[list, str]
    :return: QuerySet
    :rtype: QuerySet
    """
    if not isinstance(related, list):
        related = [related]
    related = cast(list, extract_access_chains(related))

    related = sorted(list(set(list(self._select_related) + related)))
    return self.rebuild_self(select_related=related)

sum(columns) async

Returns sum value of columns for rows matching the given criteria (applied with filter and exclude if set before).

Returns:

Type Description
int

sum value of columns

Source code in ormar/queryset/queryset.py
Python
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
async def sum(self, columns: Union[str, list[str]]) -> Any:  # noqa: A003
    """
    Returns sum value of columns for rows matching the given criteria
    (applied with `filter` and `exclude` if set before).

    :return: sum value of columns
    :rtype: int
    """
    if not isinstance(columns, list):
        columns = [columns]
    return await self._query_aggr_function(func_name="sum", columns=columns)

update(each=False, **kwargs) async

Updates the model table after applying the filters from kwargs.

You have to either pass a filter to narrow down a query or explicitly pass each=True flag to affect whole table.

Filters on related models (filter(album__name="A")) are supported, the update touches the rows the same filters select in all() (limit and offset do not apply). Expressions may read fields of models reached through foreign keys (position=F("album__rank")); rows without a related row on such a path are not updated and not counted.

Parameters:

Name Type Description Default
each bool

flag if whole table should be affected if no filter is passed

False
kwargs Any

fields names and proper value types, or column expressions (taken=Slot.taken + 1, position=F("album__rank"))

{}

Returns:

Type Description
int

number of updated rows

Raises:

Type Description
QueryDefinitionError

if an expression sets a relation, reads a reverse or many to many relation or reads another column set by this update

Source code in ormar/queryset/queryset.py
Python
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
async def update(self, each: bool = False, **kwargs: Any) -> int:
    """
    Updates the model table after applying the filters from kwargs.

    You have to either pass a filter to narrow down a query or explicitly pass
    each=True flag to affect whole table.

    Filters on related models (``filter(album__name="A")``) are supported,
    the update touches the rows the same filters select in ``all()`` (limit
    and offset do not apply). Expressions may read fields of models reached
    through foreign keys (``position=F("album__rank")``); rows without a
    related row on such a path are not updated and not counted.

    :param each: flag if whole table should be affected if no filter is passed
    :type each: bool
    :param kwargs: fields names and proper value types, or column expressions
        (``taken=Slot.taken + 1``, ``position=F("album__rank")``)
    :type kwargs: Any
    :raises QueryDefinitionError: if an expression sets a relation, reads a
        reverse or many to many relation or reads another column set by
        this update
    :return: number of updated rows
    :rtype: int
    """
    updates = self.update_values(each=each, values=kwargs)
    template = self.build_write_template(statement=UpdateWrite, values=updates)
    async with self.model_config.database.get_query_executor() as executor:
        return await executor.execute(template.statement, template.params)

update_locked_rows(updates) async

Update the rows of update_returning() without RETURNING, in the open transaction or a new one, and return them as stored::

Text Only
1
2
3
SELECT tracks.id FROM tracks WHERE <filters> FOR UPDATE OF tracks
UPDATE tracks SET ... WHERE tracks.id IN (<locked keys>)
SELECT tracks.* FROM tracks WHERE tracks.id IN (<locked keys>) FOR UPDATE

The lock keeps other transactions from changing the rows in between, and the locking read back sees the latest committed versions (not the snapshot of a REPEATABLE READ transaction), so the rows read back are the rows as this update left them.

Parameters:

Name Type Description Default
updates dict

updated values by column name

required

Returns:

Type Description
list

rows of the updated models

Source code in ormar/queryset/queryset.py
Python
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
async def update_locked_rows(self, updates: dict) -> list:
    """
    Update the rows of ``update_returning()`` without ``RETURNING``, in the
    open transaction or a new one, and return them as stored::

        SELECT tracks.id FROM tracks WHERE <filters> FOR UPDATE OF tracks
        UPDATE tracks SET ... WHERE tracks.id IN (<locked keys>)
        SELECT tracks.* FROM tracks WHERE tracks.id IN (<locked keys>) FOR UPDATE

    The lock keeps other transactions from changing the rows in between,
    and the locking read back sees the latest committed versions (not the
    snapshot of a REPEATABLE READ transaction), so the rows read back are
    the rows as this update left them.

    :param updates: updated values by column name
    :type updates: dict
    :return: rows of the updated models
    :rtype: list
    """
    lock = self.build_write_template(statement=LockWrite, values=updates)
    update = self.build_write_template(statement=UpdateLockedWrite, values=updates)
    aliases = self.model_config.pk.column_aliases()
    async with self.model_config.database.get_query_executor(
        transactional=True
    ) as executor:
        locked = await executor.fetch_all(lock.statement, lock.params)
        if not locked:
            return []
        keys = [tuple(row[alias] for alias in aliases) for row in locked]
        if len(aliases) == 1:
            keys = [key[0] for key in keys]
        await executor.execute(update.statement, {**update.params, PKS_SLOT: keys})
        rows = row_template(statement=RowsLockWrite, model_cls=self.model, pk=keys)
        return await executor.fetch_all(rows.statement, rows.params)

update_or_create(**kwargs) async

Updates the model, or in case there is no match in database creates a new one.

If a pk is supplied but no row exists with that pk, a new row is created with the supplied pk and field values rather than raising NoMatch.

Parameters:

Name Type Description Default
kwargs Any

fields names and proper value types

{}

Returns:

Type Description
Model

updated or created model

Source code in ormar/queryset/queryset.py
Python
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
async def update_or_create(self, **kwargs: Any) -> "T":
    """
    Updates the model, or in case there is no match in database creates a new one.

    If a pk is supplied but no row exists with that pk, a new row is
    created with the supplied pk and field values rather than raising
    ``NoMatch``.

    :param kwargs: fields names and proper value types
    :type kwargs: Any
    :return: updated or created model
    :rtype: Model
    """
    key = self.model_config.pk
    kwargs = key.expand_pk_kwarg(kwargs=kwargs)
    lookup = key.lookup(kwargs=kwargs)
    if lookup is None:
        return await self.create(**kwargs)
    try:
        model = await self.get(**lookup)
    except NoMatch:
        return await self.create(**kwargs)
    return await model.update(_partial=True, **kwargs)

update_returning(each=False, **kwargs) async

Updates the rows like update() and returns them as stored after the update::

Text Only
1
2
3
expired = await Booking.objects.filter(status="waitlist").update_returning(
    status="expired"
)

The models hold the columns of the model's own table only: relations are not loaded, foreign keys are models with only the primary key set, like all() without select_related. fields(), select_related() and the ordering of the queryset do not apply, the rows come back in no particular order. No signals are sent.

PostgreSQL and SQLite (3.35+) run one UPDATE ... RETURNING. MySQL has no RETURNING: in the open transaction, or a new one, the rows are selected FOR UPDATE, updated and read back by primary key.

Parameters:

Name Type Description Default
each bool

flag if whole table should be affected if no filter is passed

False
kwargs Any

fields names and proper value types, or column expressions

{}

Returns:

Type Description
list[Model]

updated models

Raises:

Type Description
QueryDefinitionError

like update()

Source code in ormar/queryset/queryset.py
Python
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
async def update_returning(self, each: bool = False, **kwargs: Any) -> list["T"]:
    """
    Updates the rows like ``update()`` and returns them as stored after the
    update::

        expired = await Booking.objects.filter(status="waitlist").update_returning(
            status="expired"
        )

    The models hold the columns of the model's own table only: relations
    are not loaded, foreign keys are models with only the primary key set,
    like ``all()`` without ``select_related``. ``fields()``,
    ``select_related()`` and the ordering of the queryset do not apply,
    the rows come back in no particular order. No signals are sent.

    PostgreSQL and SQLite (3.35+) run one ``UPDATE ... RETURNING``. MySQL
    has no ``RETURNING``: in the open transaction, or a new one, the rows
    are selected ``FOR UPDATE``, updated and read back by primary key.

    :param each: flag if whole table should be affected if no filter is passed
    :type each: bool
    :param kwargs: fields names and proper value types, or column expressions
    :type kwargs: Any
    :raises QueryDefinitionError: like ``update()``
    :return: updated models
    :rtype: list[Model]
    """
    updates = self.update_values(each=each, values=kwargs)
    database = self.model_config.database
    if database.rules.update_returning:
        template = self.build_write_template(
            statement=UpdateReturningWrite, values=updates
        )
        async with database.get_query_executor() as executor:
            rows = await executor.fetch_all(template.statement, template.params)
    else:
        rows = await self.update_locked_rows(updates=updates)
    return await QuerySet(model_cls=self.model)._process_query_result_rows(rows)

update_values(each, values)

Check an update() and turn its keyword arguments into the values to write, by column name: own fields only, on_update values added, plain values validated and converted, expressions as expression nodes.

Parameters:

Name Type Description Default
each bool

flag if whole table should be affected if no filter is passed

required
values dict

keyword arguments of the update

required

Returns:

Type Description
dict

values to write by column name

Raises:

Type Description
QueryDefinitionError

if the queryset has no filters and each is not set, or an expression is not allowed (see update())

Source code in ormar/queryset/queryset.py
Python
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
def update_values(self, each: bool, values: dict) -> dict:
    """
    Check an ``update()`` and turn its keyword arguments into the values
    to write, by column name: own fields only, ``on_update`` values added,
    plain values validated and converted, expressions as expression nodes.

    :param each: flag if whole table should be affected if no filter is passed
    :type each: bool
    :param values: keyword arguments of the update
    :type values: dict
    :raises QueryDefinitionError: if the queryset has no filters and
        ``each`` is not set, or an expression is not allowed (see
        ``update()``)
    :return: values to write by column name
    :rtype: dict
    """
    self.model.verify_writable()
    if not each and not (self.filter_clauses or self.exclude_clauses):
        raise QueryDefinitionError(
            "You cannot update without filtering the queryset first. "
            "If you want to update all rows pass each=True."
        )

    self_fields = self.model.extract_db_own_fields().union(
        self.model.extract_related_names()
    )
    updates = {
        field_name: value
        for field_name, value in values.items()
        if field_name in self_fields
    }
    updates = self.model.populate_onupdate_value(updates)
    expressions = {
        field_name: value._node()
        for field_name, value in updates.items()
        if isinstance(value, Expression)
    }
    for name, node in expressions.items():
        columns = expression_columns(node=node, model=self.model)
        for column in columns.values():
            # only validates the path here, the joins are built with the statement
            forward_join_conditions(model=self.model, path=column.related_parts)
        read = [
            column.field_name
            for column in columns.values()
            if not column.related_parts
        ]
        if name in self.model.extract_related_names() or any(
            field != name and field in updates for field in read
        ):
            raise QueryDefinitionError(
                f"update() cannot set '{name}' from an expression reading "
                f"{read}: expressions set no relations and read no columns "
                f"set by the same update."
            )
    updates = self.model.validate_update_values(
        {
            field_name: value
            for field_name, value in updates.items()
            if field_name not in expressions
        }
    )
    updates = self.model.reconvert_str_to_bytes(updates)
    updates = self.model.translate_columns_to_aliases({**updates, **expressions})
    unconsumed = [name for name in updates if name not in self.table.c]
    if unconsumed:
        raise sqlalchemy.exc.CompileError(
            f"Unconsumed column names: {', '.join(unconsumed)}"
        )
    return updates

values(fields=None, exclude_through=False, _as_dict=True, _flatten=False) async

Return a list of dictionaries with column values in order of the fields passed or all fields from queried models.

To filter for given row use filter/exclude methods before values, to limit number of rows use limit/offset or paginate before values.

Note that it always return a list even for one row from database.

Parameters:

Name Type Description Default
exclude_through bool

flag if through models should be excluded

False
_flatten bool

internal parameter to flatten one element tuples

False
_as_dict bool

internal parameter if return dict or tuples

True
fields Union[list, str, set, dict, None]

field name or list of field names to extract from db

None
Source code in ormar/queryset/queryset.py
Python
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
async def values(
    self,
    fields: Union[list, str, set, dict, None] = None,
    exclude_through: bool = False,
    _as_dict: bool = True,
    _flatten: bool = False,
) -> list:
    """
    Return a list of dictionaries with column values in order of the fields
    passed or all fields from queried models.

    To filter for given row use filter/exclude methods before values,
    to limit number of rows use limit/offset or paginate before values.

    Note that it always return a list even for one row from database.

    :param exclude_through: flag if through models should be excluded
    :type exclude_through: bool
    :param _flatten: internal parameter to flatten one element tuples
    :type _flatten: bool
    :param _as_dict: internal parameter if return dict or tuples
    :type _as_dict: bool
    :param fields: field name or list of field names to extract from db
    :type fields:  Union[list, str, set, dict]
    """
    if fields:
        return await self.fields(columns=fields).values(
            _as_dict=_as_dict, _flatten=_flatten, exclude_through=exclude_through
        )
    missing_joins = self._excludable.included_relation_paths().difference(
        self._select_related
    )
    if missing_joins:
        return await self.select_related(related=sorted(missing_joins)).values(
            _as_dict=_as_dict, _flatten=_flatten, exclude_through=exclude_through
        )
    excludable = self._excludable.with_projection_exclusions(
        source_model=self.model,
        select_related=self._select_related,
    )
    projected = (
        self
        if excludable is self._excludable
        else self.rebuild_self(excludable=excludable)
    )
    template = projected.build_select_template()
    async with self.model_config.database.get_query_executor() as executor:
        rows = await executor.fetch_all(template.statement, template.params)
    if not rows:
        return []
    columns = values_column_map(
        model_cls=self.model_cls,  # type: ignore
        select_related=self._select_related,
        excludable=excludable,
        exclude_through=exclude_through,
        column_names=list(rows[0].keys()),  # type: ignore
    )
    result = extract_values(rows=rows, columns=columns, as_dict=_as_dict)
    if _as_dict:
        return result
    if _flatten and self._excludable.include_entry_count() != 1:
        raise QueryDefinitionError(
            "You cannot flatten values_list if more than one field is selected!"
        )
    return result if not _flatten else [x[0] for x in result]

values_list(fields=None, flatten=False, exclude_through=False) async

Return a list of tuples with column values in order of the fields passed or all fields from queried models.

When one field is passed you can flatten the list of tuples into list of values of that single field.

To filter for given row use filter/exclude methods before values, to limit number of rows use limit/offset or paginate before values.

Note that it always return a list even for one row from database.

Parameters:

Name Type Description Default
exclude_through bool

flag if through models should be excluded

False
fields Union[list, str, set, dict, None]

field name or list of field names to extract from db

None
flatten bool

when one field is passed you can flatten the list of tuples

False
Source code in ormar/queryset/queryset.py
Python
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
async def values_list(
    self,
    fields: Union[list, str, set, dict, None] = None,
    flatten: bool = False,
    exclude_through: bool = False,
) -> list:
    """
    Return a list of tuples with column values in order of the fields passed or
    all fields from queried models.

    When one field is passed you can flatten the list of tuples into list of values
    of that single field.

    To filter for given row use filter/exclude methods before values,
    to limit number of rows use limit/offset or paginate before values.

    Note that it always return a list even for one row from database.

    :param exclude_through: flag if through models should be excluded
    :type exclude_through: bool
    :param fields: field name or list of field names to extract from db
    :type fields: Union[str, list[str]]
    :param flatten: when one field is passed you can flatten the list of tuples
    :type flatten: bool
    """
    return await self.values(
        fields=fields,
        exclude_through=exclude_through,
        _as_dict=False,
        _flatten=flatten,
    )

Random

Bases: Expression

Random float from 0 (inclusive) to 1 (exclusive), drawn by the database for each row: update(each=True, score=Random()), Random() * 100.

Source code in ormar/queryset/expressions.py
Python
191
192
193
194
195
class Random(Expression):
    """
    Random float from 0 (inclusive) to 1 (exclusive), drawn by the database
    for each row: ``update(each=True, score=Random())``, ``Random() * 100``.
    """

RandomOrder

Random order of the queried model, the ormar.random() form of order_by("?").

Source code in ormar/queryset/actions/order_action.py
Python
248
249
250
251
252
253
254
255
class RandomOrder:
    """
    Random order of the queried model, the ``ormar.random()`` form of
    ``order_by("?")``.
    """

    def __repr__(self) -> str:
        return "ormar.random()"

ReadOnlyModelError

Bases: ModelDefinitionError

Raised when writing to a read-only model, e.g. one mapped to a database view (OrmarConfig(view=True)).

Source code in ormar/exceptions.py
Python
26
27
28
29
30
31
32
class ReadOnlyModelError(ModelDefinitionError):
    """
    Raised when writing to a read-only model, e.g. one mapped to a database
    view (``OrmarConfig(view=True)``).
    """

    pass

ReferentialAction

Bases: Enum

Because the database management system(DBMS) enforces referential constraints, it must ensure data integrity if rows in a referenced table are to be deleted (or updated).

If dependent rows in referencing tables still exist, those references have to be considered.

SQL specifies 5 different referential actions that shall take place in such occurrences.

Source code in ormar/fields/referential_actions.py
Python
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class ReferentialAction(Enum):
    """
    Because the database management system(DBMS) enforces referential constraints,
    it must ensure data integrity
    if rows in a referenced table are to be deleted (or updated).

    If dependent rows in referencing tables still exist,
    those references have to be considered.

    SQL specifies 5 different referential actions
    that shall take place in such occurrences.
    """

    CASCADE = "CASCADE"
    RESTRICT = "RESTRICT"
    SET_NULL = "SET NULL"
    SET_DEFAULT = "SET DEFAULT"
    DO_NOTHING = "NO ACTION"

RelationType

Bases: Enum

Different types of relations supported by ormar:

  • ForeignKey and both sides of OneToOne = PRIMARY
  • reverse ForeignKey = REVERSE
  • ManyToMany = MULTIPLE
  • field leading to a through model = THROUGH
Source code in ormar/relations/relation.py
Python
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class RelationType(Enum):
    """
    Different types of relations supported by ormar:

    *  ForeignKey and both sides of OneToOne = PRIMARY
    *  reverse ForeignKey = REVERSE
    *  ManyToMany = MULTIPLE
    *  field leading to a through model = THROUGH
    """

    PRIMARY = 1
    REVERSE = 2
    MULTIPLE = 3
    THROUGH = 4

Signal

Signal that notifies all receiver functions. In ormar used by models to send pre_save, post_save etc. signals.

Source code in ormar/signals/signal.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
class Signal:
    """
    Signal that notifies all receiver functions.
    In ormar used by models to send pre_save, post_save etc. signals.
    """

    def __init__(self) -> None:
        self._receivers: dict[Union[int, tuple[int, int]], Callable] = {}

    def connect(self, receiver: Callable) -> None:
        """
        Connects given receiver function to the signal.

        :raises SignalDefinitionError: if receiver is not callable
        or not accept **kwargs
        :param receiver: receiver function
        :type receiver: Callable
        """
        if not callable(receiver):
            raise SignalDefinitionError("Signal receivers must be callable.")
        if not callable_accepts_kwargs(receiver):
            raise SignalDefinitionError(
                "Signal receivers must accept **kwargs argument."
            )
        new_receiver_key = make_id(receiver)
        if new_receiver_key not in self._receivers:
            self._receivers[new_receiver_key] = receiver

    def disconnect(self, receiver: Callable) -> bool:
        """
        Removes the receiver function from the signal.

        :param receiver: receiver function
        :type receiver: Callable
        :return: flag if receiver was removed
        :rtype: bool
        """
        new_receiver_key = make_id(receiver)
        receiver_func: Union[Callable, None] = self._receivers.pop(
            new_receiver_key, None
        )
        return True if receiver_func is not None else False

    async def send(self, sender: type["Model"], **kwargs: Any) -> None:
        """
        Notifies all receiver functions with given kwargs
        :param sender: model that sends the signal
        :type sender: type["Model"]
        :param kwargs: arguments passed to receivers
        :type kwargs: Any
        """
        if not self._receivers:
            return
        receivers = [
            receiver_func(sender=sender, **kwargs)
            for receiver_func in self._receivers.values()
        ]
        await asyncio.gather(*receivers)

connect(receiver)

Connects given receiver function to the signal.

Parameters:

Name Type Description Default
receiver Callable

receiver function

required

Raises:

Type Description
SignalDefinitionError

if receiver is not callable or not accept **kwargs

Source code in ormar/signals/signal.py
Python
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
def connect(self, receiver: Callable) -> None:
    """
    Connects given receiver function to the signal.

    :raises SignalDefinitionError: if receiver is not callable
    or not accept **kwargs
    :param receiver: receiver function
    :type receiver: Callable
    """
    if not callable(receiver):
        raise SignalDefinitionError("Signal receivers must be callable.")
    if not callable_accepts_kwargs(receiver):
        raise SignalDefinitionError(
            "Signal receivers must accept **kwargs argument."
        )
    new_receiver_key = make_id(receiver)
    if new_receiver_key not in self._receivers:
        self._receivers[new_receiver_key] = receiver

disconnect(receiver)

Removes the receiver function from the signal.

Parameters:

Name Type Description Default
receiver Callable

receiver function

required

Returns:

Type Description
bool

flag if receiver was removed

Source code in ormar/signals/signal.py
Python
69
70
71
72
73
74
75
76
77
78
79
80
81
82
def disconnect(self, receiver: Callable) -> bool:
    """
    Removes the receiver function from the signal.

    :param receiver: receiver function
    :type receiver: Callable
    :return: flag if receiver was removed
    :rtype: bool
    """
    new_receiver_key = make_id(receiver)
    receiver_func: Union[Callable, None] = self._receivers.pop(
        new_receiver_key, None
    )
    return True if receiver_func is not None else False

send(sender, **kwargs) async

Notifies all receiver functions with given kwargs

Parameters:

Name Type Description Default
sender type[Model]

model that sends the signal

required
kwargs Any

arguments passed to receivers

{}
Source code in ormar/signals/signal.py
Python
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
async def send(self, sender: type["Model"], **kwargs: Any) -> None:
    """
    Notifies all receiver functions with given kwargs
    :param sender: model that sends the signal
    :type sender: type["Model"]
    :param kwargs: arguments passed to receivers
    :type kwargs: Any
    """
    if not self._receivers:
        return
    receivers = [
        receiver_func(sender=sender, **kwargs)
        for receiver_func in self._receivers.values()
    ]
    await asyncio.gather(*receivers)

SmallInteger

Bases: Integer, int

SmallInteger field factory that construct Field classes and populated their values.

Source code in ormar/fields/model_fields.py
Python
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
class SmallInteger(Integer, int):
    """
    SmallInteger field factory that construct Field classes and populated their values.
    """

    _type = int
    _sample = 0

    @classmethod
    def get_column_type(cls, **kwargs: Any) -> Any:
        """
        Return proper type of db column for given field type.
        Accepts required and optional parameters that each column type accepts.

        :param kwargs: key, value pairs of sqlalchemy options
        :type kwargs: Any
        :return: initialized column with proper options
        :rtype: sqlalchemy Column
        """
        return unsigned_on_mysql(
            sqlalchemy.SmallInteger(), mysql.SMALLINT, kwargs.get("unsigned", False)
        )

get_column_type(**kwargs) classmethod

Return proper type of db column for given field type. Accepts required and optional parameters that each column type accepts.

Parameters:

Name Type Description Default
kwargs Any

key, value pairs of sqlalchemy options

{}

Returns:

Type Description
sqlalchemy Column

initialized column with proper options

Source code in ormar/fields/model_fields.py
Python
624
625
626
627
628
629
630
631
632
633
634
635
636
637
@classmethod
def get_column_type(cls, **kwargs: Any) -> Any:
    """
    Return proper type of db column for given field type.
    Accepts required and optional parameters that each column type accepts.

    :param kwargs: key, value pairs of sqlalchemy options
    :type kwargs: Any
    :return: initialized column with proper options
    :rtype: sqlalchemy Column
    """
    return unsigned_on_mysql(
        sqlalchemy.SmallInteger(), mysql.SMALLINT, kwargs.get("unsigned", False)
    )

String

Bases: ModelFieldFactory, str

String field factory that construct Field classes and populated their values.

Source code in ormar/fields/model_fields.py
Python
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
class String(ModelFieldFactory, str):
    """
    String field factory that construct Field classes and populated their values.
    """

    _type = str
    _sample = "string"

    def __new__(  # type: ignore # noqa CFQ002
        cls,
        *,
        max_length: int,
        min_length: Optional[int] = None,
        regex: Optional[str] = None,
        **kwargs: Any,
    ) -> Self:  # type: ignore
        kwargs = {
            **kwargs,
            **{
                k: v
                for k, v in locals().items()
                if k not in ["cls", "__class__", "kwargs"]
            },
        }
        return super().__new__(cls, **kwargs)

    @classmethod
    def get_column_type(cls, **kwargs: Any) -> Any:
        """
        Return proper type of db column for given field type.
        Accepts required and optional parameters that each column type accepts.

        :param kwargs: key, value pairs of sqlalchemy options
        :type kwargs: Any
        :return: initialized column with proper options
        :rtype: sqlalchemy Column
        """
        return sqlalchemy.String(length=kwargs.get("max_length"))

    @classmethod
    def validate(cls, **kwargs: Any) -> None:
        """
        Used to validate if all required parameters on a given field type are set.
        :param kwargs: all params passed during construction
        :type kwargs: Any
        """
        max_length = kwargs.get("max_length", -1)
        if max_length <= 0:
            raise ModelDefinitionError(
                "Parameter max_length is required for field String"
            )

get_column_type(**kwargs) classmethod

Return proper type of db column for given field type. Accepts required and optional parameters that each column type accepts.

Parameters:

Name Type Description Default
kwargs Any

key, value pairs of sqlalchemy options

{}

Returns:

Type Description
sqlalchemy Column

initialized column with proper options

Source code in ormar/fields/model_fields.py
Python
181
182
183
184
185
186
187
188
189
190
191
192
@classmethod
def get_column_type(cls, **kwargs: Any) -> Any:
    """
    Return proper type of db column for given field type.
    Accepts required and optional parameters that each column type accepts.

    :param kwargs: key, value pairs of sqlalchemy options
    :type kwargs: Any
    :return: initialized column with proper options
    :rtype: sqlalchemy Column
    """
    return sqlalchemy.String(length=kwargs.get("max_length"))

validate(**kwargs) classmethod

Used to validate if all required parameters on a given field type are set.

Parameters:

Name Type Description Default
kwargs Any

all params passed during construction

{}
Source code in ormar/fields/model_fields.py
Python
194
195
196
197
198
199
200
201
202
203
204
205
@classmethod
def validate(cls, **kwargs: Any) -> None:
    """
    Used to validate if all required parameters on a given field type are set.
    :param kwargs: all params passed during construction
    :type kwargs: Any
    """
    max_length = kwargs.get("max_length", -1)
    if max_length <= 0:
        raise ModelDefinitionError(
            "Parameter max_length is required for field String"
        )

Text

Bases: ModelFieldFactory, str

Text field factory that construct Field classes and populated their values.

Source code in ormar/fields/model_fields.py
Python
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 Text(ModelFieldFactory, str):
    """
    Text field factory that construct Field classes and populated their values.
    """

    _type = str
    _sample = "text"

    def __new__(cls, **kwargs: Any) -> Self:  # type: ignore
        kwargs = {
            **kwargs,
            **{
                k: v
                for k, v in locals().items()
                if k not in ["cls", "__class__", "kwargs"]
            },
        }
        return super().__new__(cls, **kwargs)

    @classmethod
    def get_column_type(cls, **kwargs: Any) -> Any:
        """
        Return proper type of db column for given field type.
        Accepts required and optional parameters that each column type accepts.

        :param kwargs: key, value pairs of sqlalchemy options
        :type kwargs: Any
        :return: initialized column with proper options
        :rtype: sqlalchemy Column
        """
        return sqlalchemy.Text()

get_column_type(**kwargs) classmethod

Return proper type of db column for given field type. Accepts required and optional parameters that each column type accepts.

Parameters:

Name Type Description Default
kwargs Any

key, value pairs of sqlalchemy options

{}

Returns:

Type Description
sqlalchemy Column

initialized column with proper options

Source code in ormar/fields/model_fields.py
Python
351
352
353
354
355
356
357
358
359
360
361
362
@classmethod
def get_column_type(cls, **kwargs: Any) -> Any:
    """
    Return proper type of db column for given field type.
    Accepts required and optional parameters that each column type accepts.

    :param kwargs: key, value pairs of sqlalchemy options
    :type kwargs: Any
    :return: initialized column with proper options
    :rtype: sqlalchemy Column
    """
    return sqlalchemy.Text()

Time

Bases: ModelFieldFactory, time

Time field factory that construct Field classes and populated their values.

Source code in ormar/fields/model_fields.py
Python
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
class Time(ModelFieldFactory, datetime.time):
    """
    Time field factory that construct Field classes and populated their values.
    """

    _type = datetime.time
    _sample = "time"

    def __new__(  # type: ignore # noqa CFQ002
        cls, *, timezone: bool = False, **kwargs: Any
    ) -> Self:  # type: ignore
        kwargs = {
            **kwargs,
            **{
                k: v
                for k, v in locals().items()
                if k not in ["cls", "__class__", "kwargs"]
            },
        }
        return super().__new__(cls, **kwargs)

    @classmethod
    def get_column_type(cls, **kwargs: Any) -> Any:
        """
        Return proper type of db column for given field type.
        Accepts required and optional parameters that each column type accepts.

        :param kwargs: key, value pairs of sqlalchemy options
        :type kwargs: Any
        :return: initialized column with proper options
        :rtype: sqlalchemy Column
        """
        return sqlalchemy.Time(timezone=kwargs.get("timezone", False))

get_column_type(**kwargs) classmethod

Return proper type of db column for given field type. Accepts required and optional parameters that each column type accepts.

Parameters:

Name Type Description Default
kwargs Any

key, value pairs of sqlalchemy options

{}

Returns:

Type Description
sqlalchemy Column

initialized column with proper options

Source code in ormar/fields/model_fields.py
Python
507
508
509
510
511
512
513
514
515
516
517
518
@classmethod
def get_column_type(cls, **kwargs: Any) -> Any:
    """
    Return proper type of db column for given field type.
    Accepts required and optional parameters that each column type accepts.

    :param kwargs: key, value pairs of sqlalchemy options
    :type kwargs: Any
    :return: initialized column with proper options
    :rtype: sqlalchemy Column
    """
    return sqlalchemy.Time(timezone=kwargs.get("timezone", False))

UUID

Bases: ModelFieldFactory, UUID

UUID field factory that construct Field classes and populated their values.

Source code in ormar/fields/model_fields.py
Python
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
class UUID(ModelFieldFactory, uuid.UUID):
    """
    UUID field factory that construct Field classes and populated their values.
    """

    _type = uuid.UUID
    _sample = "uuid"

    def __new__(  # type: ignore # noqa CFQ002
        cls, *, uuid_format: str = "hex", **kwargs: Any
    ) -> Self:
        kwargs = {
            **kwargs,
            **{
                k: v
                for k, v in locals().items()
                if k not in ["cls", "__class__", "kwargs"]
            },
        }

        return super().__new__(cls, **kwargs)

    @classmethod
    def get_column_type(cls, **kwargs: Any) -> Any:
        """
        Return proper type of db column for given field type.
        Accepts required and optional parameters that each column type accepts.

        :param kwargs: key, value pairs of sqlalchemy options
        :type kwargs: Any
        :return: initialized column with proper options
        :rtype: sqlalchemy Column
        """
        uuid_format = kwargs.get("uuid_format", "hex")
        return sqlalchemy_uuid.UUID(uuid_format=uuid_format)

get_column_type(**kwargs) classmethod

Return proper type of db column for given field type. Accepts required and optional parameters that each column type accepts.

Parameters:

Name Type Description Default
kwargs Any

key, value pairs of sqlalchemy options

{}

Returns:

Type Description
sqlalchemy Column

initialized column with proper options

Source code in ormar/fields/model_fields.py
Python
735
736
737
738
739
740
741
742
743
744
745
746
747
@classmethod
def get_column_type(cls, **kwargs: Any) -> Any:
    """
    Return proper type of db column for given field type.
    Accepts required and optional parameters that each column type accepts.

    :param kwargs: key, value pairs of sqlalchemy options
    :type kwargs: Any
    :return: initialized column with proper options
    :rtype: sqlalchemy Column
    """
    uuid_format = kwargs.get("uuid_format", "hex")
    return sqlalchemy_uuid.UUID(uuid_format=uuid_format)

UniqueColumns

Bases: UniqueConstraint

Subclass of sqlalchemy.UniqueConstraint. Used to avoid importing anything from sqlalchemy by user.

Source code in ormar/fields/constraints.py
Python
 6
 7
 8
 9
10
class UniqueColumns(UniqueConstraint):
    """
    Subclass of sqlalchemy.UniqueConstraint.
    Used to avoid importing anything from sqlalchemy by user.
    """

ForeignKey(to, *, name=None, unique=False, nullable=None, related_name=None, virtual=False, onupdate=None, ondelete=None, foreign_key_name=None, **kwargs)

Python
ForeignKey(to: type[T], **kwargs: Any) -> T
Python
ForeignKey(to: ForwardRef, **kwargs: Any) -> Model

Despite a name it's a function that returns constructed ForeignKeyField. This function is actually used in model declaration (as ormar.ForeignKey(ToModel)).

Accepts number of relation setting parameters as well as all BaseField ones.

Parameters:

Name Type Description Default
to Union[type[T], ForwardRef]

target related ormar Model

required
name Optional[str]

name of the database field - later called alias

None
unique bool

parameter passed to sqlalchemy.ForeignKey, unique flag

False
nullable Optional[bool]

marks field as optional/ required; defaults to optional, and to required for a foreign key in the primary key

None
related_name Optional[str]

name of reversed FK relation populated for you on to model

None
virtual bool

marks if relation is virtual. It is for reversed FK and auto generated FK on through model in Many2Many relations.

False
onupdate Union[ReferentialAction, str, None]

parameter passed to sqlalchemy.ForeignKey. How to treat child rows on update of parent (the one where FK is defined) model.

None
ondelete Union[ReferentialAction, str, None]

parameter passed to sqlalchemy.ForeignKey. How to treat child rows on delete of parent (the one where FK is defined) model.

None
foreign_key_name Optional[str]

optional override for the foreign key constraint name generated in migrations. Useful when the auto-generated name exceeds a database specific identifier length limit (for example MySQL 64 chars).

None
kwargs Any

all other args to be populated by BaseField

{}

Returns:

Type Description
ForeignKeyField

ormar ForeignKeyField with relation to selected model

Source code in ormar/fields/foreign_key.py
Python
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
def ForeignKey(  # type: ignore # noqa CFQ002
    to: Union[type["T"], "ForwardRef"],
    *,
    name: Optional[str] = None,
    unique: bool = False,
    nullable: Optional[bool] = None,
    related_name: Optional[str] = None,
    virtual: bool = False,
    onupdate: Union[ReferentialAction, str, None] = None,
    ondelete: Union[ReferentialAction, str, None] = None,
    foreign_key_name: Optional[str] = None,
    **kwargs: Any,
) -> "T":
    """
    Despite a name it's a function that returns constructed ForeignKeyField.
    This function is actually used in model declaration (as ormar.ForeignKey(ToModel)).

    Accepts number of relation setting parameters as well as all BaseField ones.

    :param to: target related ormar Model
    :type to: Model class
    :param name: name of the database field - later called alias
    :type name: str
    :param unique: parameter passed to sqlalchemy.ForeignKey, unique flag
    :type unique: bool
    :param nullable: marks field as optional/ required; defaults to optional,
        and to required for a foreign key in the primary key
    :type nullable: Optional[bool]
    :param related_name: name of reversed FK relation populated for you on to model
    :type related_name: str
    :param virtual: marks if relation is virtual.
    It is for reversed FK and auto generated FK on through model in Many2Many relations.
    :type virtual: bool
    :param onupdate: parameter passed to sqlalchemy.ForeignKey.
    How to treat child rows on update of parent (the one where FK is defined) model.
    :type onupdate: Union[ReferentialAction, str]
    :param ondelete: parameter passed to sqlalchemy.ForeignKey.
    How to treat child rows on delete of parent (the one where FK is defined) model.
    :type ondelete: Union[ReferentialAction, str]
    :param foreign_key_name: optional override for the foreign key constraint name
    generated in migrations. Useful when the auto-generated name exceeds a database
    specific identifier length limit (for example MySQL 64 chars).
    :type foreign_key_name: Optional[str]
    :param kwargs: all other args to be populated by BaseField
    :type kwargs: Any
    :return: ormar ForeignKeyField with relation to selected model
    :rtype: ForeignKeyField
    """

    onupdate = validate_referential_action(action=onupdate)
    ondelete = validate_referential_action(action=ondelete)

    owner = kwargs.pop("owner", None)
    self_reference = kwargs.pop("self_reference", False)

    orders_by = kwargs.pop("orders_by", None)
    related_orders_by = kwargs.pop("related_orders_by", None)

    skip_reverse = kwargs.pop("skip_reverse", False)
    skip_field = kwargs.pop("skip_field", False)

    primary_key = kwargs.pop("primary_key", False)
    if primary_key and nullable:
        raise ModelDefinitionError(
            "A foreign key that is part of the primary key cannot be nullable."
        )
    nullable = (not primary_key) if nullable is None else nullable
    sql_nullable = kwargs.pop("sql_nullable", None)
    sql_nullable = nullable if sql_nullable is None else sql_nullable

    index = kwargs.pop("index", False)
    to_field = kwargs.pop("to_field", None)
    columns = kwargs.pop("columns", None)
    if columns is not None and name is not None:
        raise ModelDefinitionError(
            "Pass either name= (one column) or columns= (column names by "
            "referenced column), not both."
        )
    db_constraint = kwargs.pop("db_constraint", True)
    if not db_constraint and (
        onupdate is not None or ondelete is not None or foreign_key_name is not None
    ):
        raise ModelDefinitionError(
            "ondelete/onupdate/foreign_key_name need a database constraint, they "
            "cannot be used with db_constraint=False."
        )

    validate_not_allowed_fields(kwargs)
    key_only_model = None
    if to.__class__ == ForwardRef:
        __type__ = to if not nullable else Optional[to]
        column_type = None
    else:
        validate_view_target(
            to=to,  # type: ignore
            virtual=virtual,
            db_constraint=db_constraint,
        )
        params = populate_fk_params_based_on_to_model(
            to=to,  # type: ignore
            nullable=nullable,
            virtual=virtual,
            to_field=to_field,
        )
        validate_link_columns(
            to=to,  # type: ignore
            to_field=to_field,
            columns=columns,
            name=name,
        )
        __type__ = params.annotation
        column_type = params.column_type
        key_only_model = params.key_only_model

    namespace = dict(
        __type__=__type__,
        to=to,
        to_key_only=key_only_model,
        through=None,
        alias=name,
        name=kwargs.pop("real_name", None),
        nullable=nullable,
        sql_nullable=sql_nullable,
        unique=unique,
        column_type=column_type,
        related_name=related_name,
        virtual=virtual,
        primary_key=primary_key,
        index=index,
        default=None,
        server_default=None,
        onupdate=onupdate,
        ondelete=ondelete,
        foreign_key_name=foreign_key_name,
        to_field=to_field,
        columns=columns,
        db_constraint=db_constraint,
        owner=owner,
        self_reference=self_reference,
        is_relation=True,
        orders_by=orders_by,
        related_orders_by=related_orders_by,
        skip_reverse=skip_reverse,
        skip_field=skip_field,
        **kwargs,
    )

    Field = type("ForeignKey", (ForeignKeyField, BaseField), {})
    return Field(**namespace)

ManyToMany(to, through=None, *, name=None, unique=False, virtual=False, **kwargs)

Python
ManyToMany(to: type[T], **kwargs: Any) -> RelationProxy[T]
Python
ManyToMany(to: ForwardRef, **kwargs: Any) -> RelationProxy

Despite a name it's a function that returns constructed ManyToManyField. This function is actually used in model declaration (as ormar.ManyToMany(ToModel, through=ThroughModel)).

Accepts number of relation setting parameters as well as all BaseField ones.

Parameters:

Name Type Description Default
to Union[type[T], ForwardRef]

target related ormar Model

required
through Optional[Union[type[T], ForwardRef]]

through model for m2m relation

None
name Optional[str]

name of the database field - later called alias

None
unique bool

parameter passed to sqlalchemy.ForeignKey, unique flag

False
virtual bool

marks if relation is virtual. It is for reversed FK and auto generated FK on through model in Many2Many relations.

False
kwargs Any

all other args to be populated by BaseField

{}

Returns:

Type Description
ManyToManyField

ormar ManyToManyField with m2m relation to selected model

Source code in ormar/fields/many_to_many.py
Python
 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
def ManyToMany(  # type: ignore
    to: Union[type["T"], "ForwardRef"],
    through: Optional[Union[type["T"], "ForwardRef"]] = None,
    *,
    name: Optional[str] = None,
    unique: bool = False,
    virtual: bool = False,
    **kwargs: Any,
) -> "RelationProxy[T]":
    """
    Despite a name it's a function that returns constructed ManyToManyField.
    This function is actually used in model declaration
    (as ormar.ManyToMany(ToModel, through=ThroughModel)).

    Accepts number of relation setting parameters as well as all BaseField ones.

    :param to: target related ormar Model
    :type to: Model class
    :param through: through model for m2m relation
    :type through: Model class
    :param name: name of the database field - later called alias
    :type name: str
    :param unique: parameter passed to sqlalchemy.ForeignKey, unique flag
    :type unique: bool
    :param virtual: marks if relation is virtual.
    It is for reversed FK and auto generated FK on through model in Many2Many relations.
    :type virtual: bool
    :param kwargs: all other args to be populated by BaseField
    :type kwargs: Any
    :return: ormar ManyToManyField with m2m relation to selected model
    :rtype: ManyToManyField
    """
    related_name = kwargs.pop("related_name", None)
    nullable = kwargs.pop("nullable", True)

    owner = kwargs.pop("owner", None)
    self_reference = kwargs.pop("self_reference", False)

    orders_by = kwargs.pop("orders_by", None)
    related_orders_by = kwargs.pop("related_orders_by", None)

    skip_reverse = kwargs.pop("skip_reverse", False)
    skip_field = kwargs.pop("skip_field", False)

    through_relation_name = kwargs.pop("through_relation_name", None)
    through_reverse_relation_name = kwargs.pop("through_reverse_relation_name", None)

    through_foreign_key_name = kwargs.pop("through_foreign_key_name", None)
    through_reverse_foreign_key_name = kwargs.pop(
        "through_reverse_foreign_key_name", None
    )

    through_relation_nullable = kwargs.pop("through_relation_nullable", True)
    through_reverse_relation_nullable = kwargs.pop(
        "through_reverse_relation_nullable", True
    )

    validate_not_allowed_fields(kwargs)
    pk_only_model = None
    if to.__class__ == ForwardRef:
        __type__ = (
            Union[to, list[to]]  # type: ignore
            if not nullable
            else Optional[Union[to, list[to]]]  # type: ignore
        )
        column_type = None
    else:
        __type__, column_type, pk_only_model = populate_m2m_params_based_on_to_model(
            to=to,  # type: ignore
            nullable=nullable,
        )
    namespace = dict(
        __type__=__type__,
        to=to,
        to_key_only=pk_only_model,
        through=through,
        alias=name,
        name=name,
        nullable=nullable,
        unique=unique,
        column_type=column_type,
        related_name=related_name,
        virtual=virtual,
        primary_key=False,
        index=False,
        default=None,
        server_default=None,
        owner=owner,
        self_reference=self_reference,
        is_relation=True,
        is_multi=True,
        orders_by=orders_by,
        related_orders_by=related_orders_by,
        skip_reverse=skip_reverse,
        skip_field=skip_field,
        through_relation_name=through_relation_name,
        through_reverse_relation_name=through_reverse_relation_name,
        through_foreign_key_name=through_foreign_key_name,
        through_reverse_foreign_key_name=through_reverse_foreign_key_name,
        through_relation_nullable=through_relation_nullable,
        through_reverse_relation_nullable=through_reverse_relation_nullable,
        **kwargs,
    )

    Field = type("ManyToMany", (ManyToManyField, BaseField), {})
    return Field(**namespace)

OneToOne(to, **kwargs)

Python
OneToOne(to: type[T], **kwargs: Any) -> T
Python
OneToOne(to: ForwardRef, **kwargs: Any) -> Model

A foreign key whose related model has at most one model pointing back at it: its column is unique (unless it is the primary key, which already is), and the reverse side holds a single model or None instead of a list. The default reverse name is the owner model name, without the trailing s.

Accepts the same arguments as ForeignKey.

Parameters:

Name Type Description Default
to Union[type[T], ForwardRef]

target related ormar Model

required
kwargs Any

ForeignKey parameters

{}

Returns:

Type Description
ForeignKeyField

ormar ForeignKeyField with a one to one relation

Source code in ormar/fields/foreign_key.py
Python
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
def OneToOne(  # type: ignore
    to: Union[type["T"], "ForwardRef"], **kwargs: Any
) -> "T":
    """
    A foreign key whose related model has at most one model pointing back at it:
    its column is unique (unless it is the primary key, which already is), and
    the reverse side holds a single model or ``None`` instead of a list. The
    default reverse name is the owner model name, without the trailing ``s``.

    Accepts the same arguments as ``ForeignKey``.

    :param to: target related ormar Model
    :type to: Model class
    :param kwargs: ``ForeignKey`` parameters
    :type kwargs: Any
    :return: ormar ForeignKeyField with a one to one relation
    :rtype: ForeignKeyField
    """
    if kwargs.get("unique") is False:
        raise ModelDefinitionError(
            "A OneToOne relation is always unique, use a ForeignKey for a "
            "non-unique relation."
        )
    if not kwargs.get("primary_key"):
        kwargs["unique"] = True
    return cast("T", ForeignKey(to=to, one_to_one=True, **kwargs))

and_(*args, **kwargs)

Construct and filter from nested groups and keyword arguments

Parameters:

Name Type Description Default
args FilterGroup

nested filter groups

()
kwargs Any

fields names and proper value types

{}

Returns:

Type Description
ormar.queryset.clause.FilterGroup

FilterGroup ready to be resolved

Source code in ormar/queryset/clause.py
Python
170
171
172
173
174
175
176
177
178
179
180
181
def and_(*args: FilterGroup, **kwargs: Any) -> FilterGroup:
    """
    Construct and filter from nested groups and keyword arguments

    :param args: nested filter groups
    :type args: tuple[FilterGroup]
    :param kwargs: fields names and proper value types
    :type kwargs: Any
    :return: FilterGroup ready to be resolved
    :rtype: ormar.queryset.clause.FilterGroup
    """
    return FilterGroup(_filter_type=FilterType.AND, *args, **kwargs)

or_(*args, **kwargs)

Construct or filter from nested groups and keyword arguments

Parameters:

Name Type Description Default
args FilterGroup

nested filter groups

()
kwargs Any

fields names and proper value types

{}

Returns:

Type Description
ormar.queryset.clause.FilterGroup

FilterGroup ready to be resolved

Source code in ormar/queryset/clause.py
Python
156
157
158
159
160
161
162
163
164
165
166
167
def or_(*args: FilterGroup, **kwargs: Any) -> FilterGroup:
    """
    Construct or filter from nested groups and keyword arguments

    :param args: nested filter groups
    :type args: tuple[FilterGroup]
    :param kwargs: fields names and proper value types
    :type kwargs: Any
    :return: FilterGroup ready to be resolved
    :rtype: ormar.queryset.clause.FilterGroup
    """
    return FilterGroup(_filter_type=FilterType.OR, *args, **kwargs)

post_bulk_update(senders)

Connect given function to all senders for post_bulk_update signal.

Parameters:

Name Type Description Default
senders Union[type[Model], list[type[Model]]]

one or a list of "Model" classes that should have the signal receiver registered

required

Returns:

Type Description
Callable

returns the original function untouched

Source code in ormar/decorators/signals.py
Python
176
177
178
179
180
181
182
183
184
185
186
def post_bulk_update(senders: Union[type["Model"], list[type["Model"]]]) -> Callable:
    """
    Connect given function to all senders for post_bulk_update signal.

    :param senders: one or a list of "Model" classes
    that should have the signal receiver registered
    :type senders: Union[type["Model"], list[type["Model"]]]
    :return: returns the original function untouched
    :rtype: Callable
    """
    return receiver(signal="post_bulk_update", senders=senders)

post_delete(senders)

Connect given function to all senders for post_delete signal.

Parameters:

Name Type Description Default
senders Union[type[Model], list[type[Model]]]

one or a list of "Model" classes that should have the signal receiver registered

required

Returns:

Type Description
Callable

returns the original function untouched

Source code in ormar/decorators/signals.py
Python
70
71
72
73
74
75
76
77
78
79
80
def post_delete(senders: Union[type["Model"], list[type["Model"]]]) -> Callable:
    """
    Connect given function to all senders for post_delete signal.

    :param senders: one or a list of "Model" classes
    that should have the signal receiver registered
    :type senders: Union[type["Model"], list[type["Model"]]]
    :return: returns the original function untouched
    :rtype: Callable
    """
    return receiver(signal="post_delete", senders=senders)

post_relation_add(senders)

Connect given function to all senders for post_relation_add signal.

Parameters:

Name Type Description Default
senders Union[type[Model], list[type[Model]]]

one or a list of "Model" classes that should have the signal receiver registered

required

Returns:

Type Description
Callable

returns the original function untouched

Source code in ormar/decorators/signals.py
Python
135
136
137
138
139
140
141
142
143
144
145
def post_relation_add(senders: Union[type["Model"], list[type["Model"]]]) -> Callable:
    """
    Connect given function to all senders for post_relation_add signal.

    :param senders: one or a list of "Model" classes
    that should have the signal receiver registered
    :type senders: Union[type["Model"], list[type["Model"]]]
    :return: returns the original function untouched
    :rtype: Callable
    """
    return receiver(signal="post_relation_add", senders=senders)

post_relation_remove(senders)

Connect given function to all senders for post_relation_remove signal.

Parameters:

Name Type Description Default
senders Union[type[Model], list[type[Model]]]

one or a list of "Model" classes that should have the signal receiver registered

required

Returns:

Type Description
Callable

returns the original function untouched

Source code in ormar/decorators/signals.py
Python
161
162
163
164
165
166
167
168
169
170
171
172
173
def post_relation_remove(
    senders: Union[type["Model"], list[type["Model"]]],
) -> Callable:
    """
    Connect given function to all senders for post_relation_remove signal.

    :param senders: one or a list of "Model" classes
    that should have the signal receiver registered
    :type senders: Union[type["Model"], list[type["Model"]]]
    :return: returns the original function untouched
    :rtype: Callable
    """
    return receiver(signal="post_relation_remove", senders=senders)

post_save(senders)

Connect given function to all senders for post_save signal.

Parameters:

Name Type Description Default
senders Union[type[Model], list[type[Model]]]

one or a list of "Model" classes that should have the signal receiver registered

required

Returns:

Type Description
Callable

returns the original function untouched

Source code in ormar/decorators/signals.py
Python
44
45
46
47
48
49
50
51
52
53
54
def post_save(senders: Union[type["Model"], list[type["Model"]]]) -> Callable:
    """
    Connect given function to all senders for post_save signal.

    :param senders: one or a list of "Model" classes
    that should have the signal receiver registered
    :type senders: Union[type["Model"], list[type["Model"]]]
    :return: returns the original function untouched
    :rtype: Callable
    """
    return receiver(signal="post_save", senders=senders)

post_update(senders)

Connect given function to all senders for post_update signal.

Parameters:

Name Type Description Default
senders Union[type[Model], list[type[Model]]]

one or a list of "Model" classes that should have the signal receiver registered

required

Returns:

Type Description
Callable

returns the original function untouched

Source code in ormar/decorators/signals.py
Python
57
58
59
60
61
62
63
64
65
66
67
def post_update(senders: Union[type["Model"], list[type["Model"]]]) -> Callable:
    """
    Connect given function to all senders for post_update signal.

    :param senders: one or a list of "Model" classes
    that should have the signal receiver registered
    :type senders: Union[type["Model"], list[type["Model"]]]
    :return: returns the original function untouched
    :rtype: Callable
    """
    return receiver(signal="post_update", senders=senders)

pre_delete(senders)

Connect given function to all senders for pre_delete signal.

Parameters:

Name Type Description Default
senders Union[type[Model], list[type[Model]]]

one or a list of "Model" classes that should have the signal receiver registered

required

Returns:

Type Description
Callable

returns the original function untouched

Source code in ormar/decorators/signals.py
Python
109
110
111
112
113
114
115
116
117
118
119
def pre_delete(senders: Union[type["Model"], list[type["Model"]]]) -> Callable:
    """
    Connect given function to all senders for pre_delete signal.

    :param senders: one or a list of "Model" classes
    that should have the signal receiver registered
    :type senders: Union[type["Model"], list[type["Model"]]]
    :return: returns the original function untouched
    :rtype: Callable
    """
    return receiver(signal="pre_delete", senders=senders)

pre_relation_add(senders)

Connect given function to all senders for pre_relation_add signal.

Parameters:

Name Type Description Default
senders Union[type[Model], list[type[Model]]]

one or a list of "Model" classes that should have the signal receiver registered

required

Returns:

Type Description
Callable

returns the original function untouched

Source code in ormar/decorators/signals.py
Python
122
123
124
125
126
127
128
129
130
131
132
def pre_relation_add(senders: Union[type["Model"], list[type["Model"]]]) -> Callable:
    """
    Connect given function to all senders for pre_relation_add signal.

    :param senders: one or a list of "Model" classes
    that should have the signal receiver registered
    :type senders: Union[type["Model"], list[type["Model"]]]
    :return: returns the original function untouched
    :rtype: Callable
    """
    return receiver(signal="pre_relation_add", senders=senders)

pre_relation_remove(senders)

Connect given function to all senders for pre_relation_remove signal.

Parameters:

Name Type Description Default
senders Union[type[Model], list[type[Model]]]

one or a list of "Model" classes that should have the signal receiver registered

required

Returns:

Type Description
Callable

returns the original function untouched

Source code in ormar/decorators/signals.py
Python
148
149
150
151
152
153
154
155
156
157
158
def pre_relation_remove(senders: Union[type["Model"], list[type["Model"]]]) -> Callable:
    """
    Connect given function to all senders for pre_relation_remove signal.

    :param senders: one or a list of "Model" classes
    that should have the signal receiver registered
    :type senders: Union[type["Model"], list[type["Model"]]]
    :return: returns the original function untouched
    :rtype: Callable
    """
    return receiver(signal="pre_relation_remove", senders=senders)

pre_save(senders)

Connect given function to all senders for pre_save signal.

Parameters:

Name Type Description Default
senders Union[type[Model], list[type[Model]]]

one or a list of "Model" classes that should have the signal receiver registered

required

Returns:

Type Description
Callable

returns the original function untouched

Source code in ormar/decorators/signals.py
Python
83
84
85
86
87
88
89
90
91
92
93
def pre_save(senders: Union[type["Model"], list[type["Model"]]]) -> Callable:
    """
    Connect given function to all senders for pre_save signal.

    :param senders: one or a list of "Model" classes
    that should have the signal receiver registered
    :type senders: Union[type["Model"], list[type["Model"]]]
    :return: returns the original function untouched
    :rtype: Callable
    """
    return receiver(signal="pre_save", senders=senders)

pre_update(senders)

Connect given function to all senders for pre_update signal.

Parameters:

Name Type Description Default
senders Union[type[Model], list[type[Model]]]

one or a list of "Model" classes that should have the signal receiver registered

required

Returns:

Type Description
Callable

returns the original function untouched

Source code in ormar/decorators/signals.py
Python
 96
 97
 98
 99
100
101
102
103
104
105
106
def pre_update(senders: Union[type["Model"], list[type["Model"]]]) -> Callable:
    """
    Connect given function to all senders for pre_update signal.

    :param senders: one or a list of "Model" classes
    that should have the signal receiver registered
    :type senders: Union[type["Model"], list[type["Model"]]]
    :return: returns the original function untouched
    :rtype: Callable
    """
    return receiver(signal="pre_update", senders=senders)

random()

Order the rows randomly, same as "?"::

Text Only
1
await User.objects.order_by(ormar.random()).limit(3).all()

Returns:

Type Description
RandomOrder

random order to pass to order_by()

Source code in ormar/queryset/actions/order_action.py
Python
258
259
260
261
262
263
264
265
266
267
def random() -> RandomOrder:
    """
    Order the rows randomly, same as ``"?"``::

        await User.objects.order_by(ormar.random()).limit(3).all()

    :return: random order to pass to ``order_by()``
    :rtype: RandomOrder
    """
    return RandomOrder()