Skip to content

helpers

building_schemas()

Marks that ormar is building pydantic schemas of its own models, so pending models embedded in them are not rebuilt but reused as they are.

Returns:

Type Description
Iterator[None]

context manager

Source code in ormar/models/helpers/rebuild.py
Python
37
38
39
40
41
42
43
44
45
46
47
48
49
50
@contextmanager
def building_schemas() -> Iterator[None]:
    """
    Marks that ormar is building pydantic schemas of its own models, so
    pending models embedded in them are not rebuilt but reused as they are.

    :return: context manager
    :rtype: Iterator[None]
    """
    token = building_schemas_var.set(True)
    try:
        yield
    finally:
        building_schemas_var.reset(token)

check_required_config_parameters(new_model)

Verifies if ormar.Model has database and metadata set.

Recreates Connection pool for sqlite3

Parameters:

Name Type Description Default
new_model type[Model]

newly declared ormar Model

required
Source code in ormar/models/helpers/models.py
Python
 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
def check_required_config_parameters(new_model: type["Model"]) -> None:
    """
    Verifies if ormar.Model has database and metadata set.

    Recreates Connection pool for sqlite3

    :param new_model: newly declared ormar Model
    :type new_model: Model class
    """
    if new_model.ormar_config.proxy and new_model.ormar_config.abstract:
        raise ormar.ModelDefinitionError(
            f"{new_model.__name__} cannot be both proxy and abstract."
        )

    skip_db_metadata_checks = (
        new_model.ormar_config.abstract or new_model.ormar_config.proxy
    )
    if new_model.ormar_config.database is None and not skip_db_metadata_checks:
        raise ormar.ModelDefinitionError(
            f"{new_model.__name__} does not have database defined."
        )

    if new_model.ormar_config.metadata is None and not skip_db_metadata_checks:
        raise ormar.ModelDefinitionError(
            f"{new_model.__name__} does not have metadata defined."
        )

config_field_not_set(model, field_name)

Checks if field with given name is already present in model.OrmarConfig. Then check if it's set to something truthful (in practice meaning not None, as it's non or ormar Field only).

Parameters:

Name Type Description Default
model type[Model]

newly constructed model

required
field_name str

name of the ormar field

required

Returns:

Type Description
bool

result of the check

Source code in ormar/models/helpers/models.py
Python
168
169
170
171
172
173
174
175
176
177
178
179
180
181
def config_field_not_set(model: type["Model"], field_name: str) -> bool:
    """
    Checks if field with given name is already present in model.OrmarConfig.
    Then check if it's set to something truthful
    (in practice meaning not None, as it's non or ormar Field only).

    :param model: newly constructed model
    :type model: Model class
    :param field_name: name of the ormar field
    :type field_name: str
    :return: result of the check
    :rtype: bool
    """
    return not getattr(model.ormar_config, field_name)

expand_reverse_relationships(model)

Iterates through model_fields of given model and verifies if all reverse relation have been populated on related models.

If the reverse relation has not been set before it's set here.

Parameters:

Name Type Description Default
model type[Model]

model on which relation should be checked and registered

required
Source code in ormar/models/helpers/relations.py
Python
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
def expand_reverse_relationships(model: type["Model"]) -> None:
    """
    Iterates through model_fields of given model and verifies if all reverse
    relation have been populated on related models.

    If the reverse relation has not been set before it's set here.

    :param model: model on which relation should be checked and registered
    :type model: Model class
    """
    model_fields = list(model.ormar_config.model_fields.values())
    for model_field in model_fields:
        if (
            model_field.is_relation
            and not model_field.has_unresolved_forward_refs()
            and not model_field.is_through
        ):
            model_field = cast("ForeignKeyField", model_field)
            expand_reverse_relationship(model_field=model_field)

extract_annotations_and_default_vals(attrs)

Extracts annotations from class namespace dict and triggers extraction of ormar model_fields.

Parameters:

Name Type Description Default
attrs dict

namespace of the class created

required

Returns:

Type Description
tuple[dict, dict]

namespace of the class updated, dict of extracted model_fields

Source code in ormar/models/helpers/models.py
Python
108
109
110
111
112
113
114
115
116
117
118
119
120
def extract_annotations_and_default_vals(attrs: dict) -> tuple[dict, dict]:
    """
    Extracts annotations from class namespace dict and triggers
    extraction of ormar model_fields.

    :param attrs: namespace of the class created
    :type attrs: dict
    :return: namespace of the class updated, dict of extracted model_fields
    :rtype: tuple[dict, dict]
    """
    attrs["__annotations__"] = get_namespace_annotations(namespace=attrs)
    attrs, model_fields = populate_pydantic_default_values(attrs)
    return attrs, model_fields

get_namespace_annotations(namespace)

Returns the annotations declared in a class namespace (or class __dict__).

Since Python 3.14 (PEP 649) a class body no longer stores __annotations__, only an annotate function, so the annotations are evaluated from it in forward-ref format (names not defined yet become ForwardRef).

Parameters:

Name Type Description Default
namespace Mapping[str, Any]

class namespace or class __dict__

required

Returns:

Type Description
dict[str, Any]

annotations declared in the namespace

Source code in ormar/models/helpers/models.py
Python
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
def get_namespace_annotations(namespace: Mapping[str, Any]) -> dict[str, Any]:
    """
    Returns the annotations declared in a class namespace (or class ``__dict__``).

    Since Python 3.14 (PEP 649) a class body no longer stores ``__annotations__``,
    only an annotate function, so the annotations are evaluated from it in
    forward-ref format (names not defined yet become ``ForwardRef``).

    :param namespace: class namespace or class ``__dict__``
    :type namespace: Mapping[str, Any]
    :return: annotations declared in the namespace
    :rtype: dict[str, Any]
    """
    annotations = namespace.get("__annotations__")
    if annotations is not None:
        return annotations
    if sys.version_info >= (3, 14):  # pragma: no cover
        annotate = annotationlib.get_annotate_from_class_namespace(obj=namespace)
        if annotate is not None:
            return annotationlib.call_annotate_function(
                annotate=annotate, format=annotationlib.Format.FORWARDREF
            )
    return {}

get_potential_fields(attrs)

Gets all the fields in current class namespace that are Fields.

Parameters:

Name Type Description Default
attrs Union[dict, MappingProxyType]

current class namespace

required

Returns:

Type Description
dict

extracted fields that are ormar Fields

Source code in ormar/models/helpers/pydantic.py
Python
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
def get_potential_fields(attrs: Union[dict, MappingProxyType]) -> dict:
    """
    Gets all the fields in current class namespace that are Fields.

    :param attrs: current class namespace
    :type attrs: dict
    :return: extracted fields that are ormar Fields
    :rtype: dict
    """
    return {
        k: v
        for k, v in attrs.items()
        if (
            (isinstance(v, type) and issubclass(v, BaseField))
            or isinstance(v, BaseField)
        )
    }

get_pydantic_base_orm_config()

Returns empty pydantic Config with orm_mode set to True.

Returns:

Type Description
pydantic Config

empty default config with orm_mode set.

Source code in ormar/models/helpers/pydantic.py
Python
100
101
102
103
104
105
106
107
108
def get_pydantic_base_orm_config() -> pydantic.ConfigDict:
    """
    Returns empty pydantic Config with orm_mode set to True.

    :return: empty default config with orm_mode set.
    :rtype: pydantic Config
    """

    return ConfigDict(validate_assignment=True, ser_json_bytes="base64")

mark_for_rebuild(model)

Marks the model as needing a pydantic rebuild instead of rebuilding it.

Schema, validator and serializer of the model are replaced with mocks that rebuild all pending connected models on first access. The previous schema is kept as a snapshot for schemas ormar builds until then.

Parameters:

Name Type Description Default
model type[Model]

model whose fields changed

required
Source code in ormar/models/helpers/rebuild.py
Python
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
def mark_for_rebuild(model: type["Model"]) -> None:
    """
    Marks the model as needing a pydantic rebuild instead of rebuilding it.

    Schema, validator and serializer of the model are replaced with mocks that
    rebuild all pending connected models on first access. The previous schema
    is kept as a snapshot for schemas ormar builds until then.

    :param model: model whose fields changed
    :type model: Model class
    """
    if PENDING_ATTR not in model.__dict__:
        schema = model.__dict__.get("__pydantic_core_schema__")
        if schema is not None and not isinstance(schema, MockCoreSchema):
            setattr(model, SNAPSHOT_ATTR, schema)
        set_rebuild_mocks(model=model)
    setattr(model, PENDING_ATTR, next(pending_order))

merge_or_generate_pydantic_config(attrs, name)

Checks if the user provided pydantic Config, and if he did merges it with the default one.

Updates the attrs in place with a new config.

Source code in ormar/models/helpers/pydantic.py
Python
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
def merge_or_generate_pydantic_config(attrs: dict, name: str) -> None:
    """
    Checks if the user provided pydantic Config,
    and if he did merges it with the default one.

    Updates the attrs in place with a new config.

    :rtype: None
    """
    default_config = get_pydantic_base_orm_config()
    if "model_config" in attrs:
        provided_config = attrs["model_config"]
        if not isinstance(provided_config, dict):
            raise ModelDefinitionError(
                f"Config provided for class {name} has to be a dictionary."
            )

        config = {**default_config, **provided_config}
        attrs["model_config"] = config
    else:
        attrs["model_config"] = default_config

modify_schema_example(model)

Modifies the schema example in openapi schema.

Parameters:

Name Type Description Default
model type[Model]

newly constructed Model

required
Source code in ormar/models/helpers/validation.py
Python
204
205
206
207
208
209
210
211
212
def modify_schema_example(model: type["Model"]) -> None:  # noqa CCR001
    """
    Modifies the schema example in openapi schema.

    :param model: newly constructed Model
    :type model: Model class
    """
    if not config_field_not_set(model=model, field_name="model_fields"):
        model.model_config["json_schema_extra"] = construct_schema_function()

populate_config_sqlalchemy_table_if_required(config)

Constructs sqlalchemy table out of columns and parameters set on OrmarConfig. It populates name, metadata, columns and constraints.

Parameters:

Name Type Description Default
config OrmarConfig

OrmarConfig of the Model without sqlalchemy table constructed

required
Source code in ormar/models/helpers/sqlalchemy.py
Python
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
def populate_config_sqlalchemy_table_if_required(config: "OrmarConfig") -> None:
    """
    Constructs sqlalchemy table out of columns and parameters set on OrmarConfig.
    It populates name, metadata, columns and constraints.

    :param config: OrmarConfig of the Model without sqlalchemy table constructed
    :type config: Model class OrmarConfig
    """
    if config.table is None and check_for_null_type_columns_from_forward_refs(
        config=config
    ):
        set_constraint_names(config=config)
        # a view gets its own metadata so create_all and Alembic leave it alone
        table = sqlalchemy.Table(
            config.tablename,
            (
                sqlalchemy.MetaData(
                    schema=config.metadata.schema,
                    naming_convention=config.metadata.naming_convention,
                )
                if config.view
                else config.metadata
            ),
            *config.columns,
            *config.constraints,
            *(
                constraint
                for field in config.model_fields.values()
                for constraint in field.construct_table_constraints()
            ),
            schema=config.schema,
            comment=config.comment,
        )
        config.table = table

populate_config_tablename_columns_and_pk(name, new_model)

Sets Model tablename if it's not already set in OrmarConfig. Default tablename if not present is class name lower + s (i.e. Bed becomes -> beds)

Checks if Model's OrmarConfig have primary key and columns set. If not calls the sqlalchemy_columns_from_model_fields to populate columns from ormar.fields definitions.

Parameters:

Name Type Description Default
name str

name of the current Model

required
new_model type[Model]

currently constructed Model

required

Returns:

Type Description
ormar.models.metaclass.ModelMetaclass

Model with populated primary key and columns in OrmarConfig

Raises:

Type Description
ModelDefinitionError

if no field is marked as primary key. Each model has to have pk.

Source code in ormar/models/helpers/sqlalchemy.py
Python
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
def populate_config_tablename_columns_and_pk(
    name: str, new_model: type["Model"]
) -> type["Model"]:
    """
    Sets Model tablename if it's not already set in OrmarConfig.
    Default tablename if not present is class name lower + s (i.e. Bed becomes -> beds)

    Checks if Model's OrmarConfig have primary key and columns set.
    If not calls the sqlalchemy_columns_from_model_fields to populate
    columns from ormar.fields definitions.

    :raises ModelDefinitionError: if no field is marked as primary key.
    Each model has to have pk.

    :param name: name of the current Model
    :type name: str
    :param new_model: currently constructed Model
    :type new_model: ormar.models.metaclass.ModelMetaclass
    :return: Model with populated primary key and columns in OrmarConfig
    :rtype: ormar.models.metaclass.ModelMetaclass
    """
    tablename = name.lower() + "s"
    new_model.ormar_config.tablename = (
        new_model.ormar_config.tablename
        if new_model.ormar_config.tablename
        else tablename
    )
    if new_model.ormar_config.columns:
        # a config with columns is shared with the model that built them
        # (e.g. pydantic copies made for circular references), keep its key
        columns = new_model.ormar_config.columns
        key = new_model.ormar_config.pk
    else:
        pk_fields, columns = sqlalchemy_columns_from_model_fields(
            model_fields=new_model.ormar_config.model_fields, new_model=new_model
        )
        if not pk_fields:
            raise ormar.ModelDefinitionError("Table has to have a primary key.")
        key = build_primary_key(owner=new_model, fields=pk_fields)
        if key.is_composite:
            prepare_composite_key_fields(key=key, columns=columns)

    new_model.ormar_config.columns = columns
    new_model.ormar_config.pk = key
    if not new_model.ormar_config.orders_by:
        # by default, we sort by the primary key if other option not provided
        new_model.ormar_config.orders_by.extend(key.fields)
    return new_model

populate_default_options_values(new_model, model_fields)

Sets all optional OrmarConfig values to its defaults and set model_fields that were already previously extracted.

Here should live all options that are not overwritten/set for all models.

Current options are: * constraints = [] * abstract = False

Parameters:

Name Type Description Default
new_model type[Model]

newly constructed Model

required
model_fields dict

dict of model fields

required
Source code in ormar/models/helpers/models.py
Python
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
def populate_default_options_values(  # noqa: CCR001
    new_model: type["Model"], model_fields: dict
) -> None:
    """
    Sets all optional OrmarConfig values to its defaults
    and set model_fields that were already previously extracted.

    Here should live all options that are not overwritten/set for all models.

    Current options are:
    * constraints = []
    * abstract = False

    :param new_model: newly constructed Model
    :type new_model: Model class
    :param model_fields: dict of model fields
    :type model_fields: Union[dict[str, type], dict]
    """
    new_model.ormar_config.model_fields.update(model_fields)
    if any(is_field_an_forward_ref(field) for field in model_fields.values()):
        new_model.ormar_config.requires_ref_update = True

    new_model._json_fields = {
        name for name, field in model_fields.items() if field.__type__ == pydantic.Json
    }
    new_model._loaded_json_fields = {
        name
        for name, field in model_fields.items()
        if name in new_model._json_fields
        and field.__pydantic_type__ == pydantic.Json
        and field.encrypt_backend == ormar.EncryptBackends.NONE
    }
    new_model._bytes_fields = {
        name for name, field in model_fields.items() if field.__type__ is bytes
    }
    new_model._onupdate_fields = {
        name for name, field in model_fields.items() if field.has_on_update()
    }

    new_model.__relation_map__ = None
    new_model.__relation_tree__ = None
    new_model.__relation_graph_version__ = RelationGraph.version
    new_model.__ormar_fields_validators__ = None

rebuild_model(model)

Rebuilds pydantic schema, validator and serializer of the model with its current fields and clears its pending rebuild mark.

If the rebuild fails (i.e. a related model still has an unresolved ForwardRef) the pending mark, snapshot and rebuild mocks are restored, so the rebuild is retried once the reference is resolved.

Parameters:

Name Type Description Default
model type[Model]

model to rebuild

required
Source code in ormar/models/helpers/rebuild.py
Python
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
def rebuild_model(model: type["Model"]) -> None:
    """
    Rebuilds pydantic schema, validator and serializer of the model with its
    current fields and clears its pending rebuild mark.

    If the rebuild fails (i.e. a related model still has an unresolved
    ForwardRef) the pending mark, snapshot and rebuild mocks are restored, so
    the rebuild is retried once the reference is resolved.

    :param model: model to rebuild
    :type model: Model class
    """
    marks = {
        attr: model.__dict__[attr]
        for attr in (PENDING_ATTR, SNAPSHOT_ATTR)
        if attr in model.__dict__
    }
    for attr in marks:
        delattr(model, attr)
    pending = PENDING_ATTR in marks
    types_namespace = {
        related.__name__: related for related in related_models(model=model)
    }
    types_namespace[model.__name__] = model
    # A pending model is already mocked, so a plain rebuild regenerates it and
    # can reuse the compiled validators of nested models rebuilt before it.
    try:
        with building_schemas():
            model.model_rebuild(force=not pending, _types_namespace=types_namespace)
    except Exception:
        if pending:
            for attr, value in marks.items():
                setattr(model, attr, value)
            set_rebuild_mocks(model=model)
        raise

rebuild_pending_models(model)

Rebuilds every pending model connected to the model, each one once with its final fields, in the order they were last marked.

That is the order in which eager rebuilds finished the models, so models rebuilt later embed the final schemas of the ones rebuilt before them and nested shapes stay close to the ones eager rebuilds produced.

While ormar builds its own schemas only the given model is rebuilt (if pending), the other ones are embedded as snapshots.

Parameters:

Name Type Description Default
model type[Model]

model whose schema is needed

required
Source code in ormar/models/helpers/rebuild.py
Python
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
def rebuild_pending_models(model: type["Model"]) -> None:
    """
    Rebuilds every pending model connected to the model, each one once with
    its final fields, in the order they were last marked.

    That is the order in which eager rebuilds finished the models, so models
    rebuilt later embed the final schemas of the ones rebuilt before them and
    nested shapes stay close to the ones eager rebuilds produced.

    While ormar builds its own schemas only the given model is rebuilt (if
    pending), the other ones are embedded as snapshots.

    :param model: model whose schema is needed
    :type model: Model class
    """
    if building_schemas_var.get():
        candidates = [model]
    else:
        candidates = connected_models(model=model)
    pending = sorted(
        (
            candidate
            for candidate in candidates
            if PENDING_ATTR in candidate.__dict__
            and not candidate.ormar_config.requires_ref_update
        ),
        key=lambda candidate: candidate.__dict__[PENDING_ATTR],
    )
    for pending_model in pending:
        rebuild_model(model=pending_model)

schema_snapshot(model)

Returns the schema the model had before it was marked as pending, used while ormar builds schemas of other models.

Parameters:

Name Type Description Default
model type[Model]

model to check

required

Returns:

Type Description
Optional[CoreSchema]

schema snapshot or None if model is not pending or had none

Source code in ormar/models/helpers/rebuild.py
Python
169
170
171
172
173
174
175
176
177
178
179
180
181
def schema_snapshot(model: type["Model"]) -> Optional[CoreSchema]:
    """
    Returns the schema the model had before it was marked as pending, used
    while ormar builds schemas of other models.

    :param model: model to check
    :type model: Model class
    :return: schema snapshot or None if model is not pending or had none
    :rtype: Optional[CoreSchema]
    """
    if not building_schemas_var.get():
        return None
    return model.__dict__.get(SNAPSHOT_ATTR)

sqlalchemy_columns_from_model_fields(model_fields, new_model)

Iterates over declared on Model model fields and extracts fields that should be treated as database fields.

If the model is empty it sets mandatory id field as primary key (used in through models in m2m relations).

Triggers a validation of relation_names in relation fields. If multiple fields are leading to the same related model only one can have empty related_name param. Also related_names have to be unique.

Sets owner on each model_field as reference to newly created Model.

Parameters:

Name Type Description Default
model_fields dict

dictionary of declared ormar model fields

required
new_model type[Model]
required

Returns:

Type Description
tuple[tuple[str, ...], list[sqlalchemy.Column]]

names of the primary key fields, list of sqlalchemy columns

Raises:

Type Description
ModelDefinitionError

if validation of related_names fail

Source code in ormar/models/helpers/sqlalchemy.py
Python
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
def sqlalchemy_columns_from_model_fields(
    model_fields: dict, new_model: type["Model"]
) -> tuple[tuple[str, ...], list[sqlalchemy.Column]]:
    """
    Iterates over declared on Model model fields and extracts fields that
    should be treated as database fields.

    If the model is empty it sets mandatory id field as primary key
    (used in through models in m2m relations).

    Triggers a validation of relation_names in relation fields. If multiple fields
    are leading to the same related model only one can have empty related_name param.
    Also related_names have to be unique.


    Sets `owner` on each model_field as reference to newly created Model.

    :raises ModelDefinitionError: if validation of related_names fail
    :param model_fields: dictionary of declared ormar model fields
    :type model_fields: dict[str, ormar.Field]
    :param new_model:
    :type new_model: Model class
    :return: names of the primary key fields, list of sqlalchemy columns
    :rtype: tuple[tuple[str, ...], list[sqlalchemy.Column]]
    """
    if len(model_fields.keys()) == 0:
        model_fields["id"] = ormar.Integer(name="id", primary_key=True)
        logging.warning(
            f"Table {new_model.ormar_config.tablename} had no fields so auto "
            "Integer primary key named `id` created."
        )
    validate_related_names_in_relations(model_fields, new_model)
    return _process_fields(model_fields=model_fields, new_model=new_model)