Skip to content

fields

Module with classes and constructors for ormar Fields. Base Fields types (like String, Integer etc.) as well as relation Fields (ForeignKey, ManyToMany). Also a definition for custom CHAR based sqlalchemy UUID field

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.
    """

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)

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))))

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)

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"
        )

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()

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"

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()

ThroughField

Bases: ForeignKeyField

Field class used to access ManyToMany model through model.

Source code in ormar/fields/through_field.py
Python
69
70
71
72
73
74
75
76
77
78
79
80
class ThroughField(ForeignKeyField):  # type: ignore[misc]
    """
    Field class used to access ManyToMany model through model.
    """

    @property
    def kind(self) -> RelationKind:
        """
        :return: ``THROUGH``, the field leading from a model to its link table
        :rtype: RelationKind
        """
        return THROUGH

kind property

Returns:

Type Description
RelationKind

THROUGH, the field leading from a model to its link table

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))

Through(to, *, name=None, related_name=None, **kwargs)

Despite a name it's a function that returns constructed ThroughField. It's a special field populated only for m2m relations. Accepts number of relation setting parameters as well as all BaseField ones.

Parameters:

Name Type Description Default
to ToType

target related ormar Model

required
name Optional[str]

name of the database field - later called alias

None
related_name Optional[str]

name of reversed FK relation populated for you on to model

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/through_field.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
def Through(  # noqa CFQ002
    to: "ToType",
    *,
    name: Optional[str] = None,
    related_name: Optional[str] = None,
    **kwargs: Any,
) -> Any:
    """
    Despite a name it's a function that returns constructed ThroughField.
    It's a special field populated only for m2m relations.
    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 related_name: name of reversed FK relation populated for you on to model
    :type related_name: str
    It is for reversed FK and auto generated FK on through model in Many2Many relations.
    :param kwargs: all other args to be populated by BaseField
    :type kwargs: Any
    :return: ormar ForeignKeyField with relation to selected model
    :rtype: ForeignKeyField
    """
    nullable = kwargs.pop("nullable", False)
    owner = kwargs.pop("owner", None)
    namespace = dict(
        __type__=to,
        to=to,
        through=None,
        alias=name,
        name=kwargs.pop("real_name", None),
        related_name=related_name,
        virtual=True,
        owner=owner,
        nullable=nullable,
        unique=False,
        column_type=None,
        primary_key=False,
        index=False,
        default=None,
        server_default=None,
        is_relation=True,
        is_through=True,
    )

    Field = type("Through", (ThroughField, BaseField), {})
    return Field(**namespace)