Skip to content

pydantic

create_pydantic_field(field_name, model, model_field)

Registers pydantic field on through model that leads to passed model and is registered as field_name passed.

Through model is fetched from through attributed on passed model_field.

Parameters:

Name Type Description Default
field_name str

field name to register

required
model type[Model]

type of field to register

required
model_field ManyToManyField

relation field from which through model is extracted

required
Source code in ormar/models/helpers/pydantic.py
Python
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
def create_pydantic_field(
    field_name: str, model: type["Model"], model_field: "ManyToManyField"
) -> None:
    """
    Registers pydantic field on through model that leads to passed model
    and is registered as field_name passed.

    Through model is fetched from through attributed on passed model_field.

    :param field_name: field name to register
    :type field_name: str
    :param model: type of field to register
    :type model: Model class
    :param model_field: relation field from which through model is extracted
    :type model_field: ManyToManyField class
    """
    model_field.through.model_fields[field_name] = FieldInfo.from_annotated_attribute(
        annotation=Optional[model],  # type: ignore
        default=None,
    )
    mark_for_rebuild(model=model_field.through)

extract_pk_value(value, fields)

Reduce a related model, its dict representation or a bare key to the value representing it in flattened output: the value of its single key field, or a dict of its key fields when there are several (a key tuple is turned into that dict).

Used as a before-validator on fields generated by get_pydantic with flatten_fields / flatten_all, so both request payloads (bare key) and dumped ormar models (nested dict or model instance) validate against the flattened type.

Parameters:

Name Type Description Default
value Any

related model instance, dict or key value

required
fields tuple[str, ...]

fields representing the related model (flat_fields())

required

Returns:

Type Description
Any

flattened value, or the original value if it cannot be reduced

Source code in ormar/models/helpers/pydantic.py
Python
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
def extract_pk_value(value: Any, fields: tuple[str, ...]) -> Any:
    """
    Reduce a related model, its dict representation or a bare key to the
    value representing it in flattened output: the value of its single key
    field, or a dict of its key fields when there are several (a key tuple is
    turned into that dict).

    Used as a before-validator on fields generated by ``get_pydantic`` with
    ``flatten_fields`` / ``flatten_all``, so both request payloads (bare key)
    and dumped ormar models (nested dict or model instance) validate against
    the flattened type.

    :param value: related model instance, dict or key value
    :type value: Any
    :param fields: fields representing the related model (``flat_fields()``)
    :type fields: tuple[str, ...]
    :return: flattened value, or the original value if it cannot be reduced
    :rtype: Any
    """
    if len(fields) > 1:
        if isinstance(value, pydantic.BaseModel):
            return {field: getattr(value, field, None) for field in fields}
        if isinstance(value, dict):
            return {field: value[field] for field in fields if field in value}
        if not isinstance(value, (tuple, list)) or len(value) != len(fields):
            raise ValueError(
                f"Expected a key of {len(fields)} values {list(fields)}, got {value!r}."
            )
        return dict(zip(fields, value))
    (pkname,) = fields
    if isinstance(value, dict):
        return value.get(pkname, value)
    if isinstance(value, pydantic.BaseModel):
        return getattr(value, pkname, value)
    return value

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

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

populate_pydantic_default_values(attrs)

Extracts ormar fields from annotations (deprecated) and from namespace dictionary of the class. Fields declared on model are all subclasses of the BaseField class.

Trigger conversion of ormar field into pydantic FieldInfo, which has all needed parameters saved.

Overwrites the annotations of ormar fields to corresponding types declared on ormar fields (constructed dynamically for relations). Those annotations are later used by pydantic to construct it's own fields.

Parameters:

Name Type Description Default
attrs dict

current class namespace

required

Returns:

Type Description
tuple[dict, dict]

namespace of the class updated, dict of extracted model_fields

Source code in ormar/models/helpers/pydantic.py
Python
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
def populate_pydantic_default_values(attrs: dict) -> tuple[dict, dict]:
    """
    Extracts ormar fields from annotations (deprecated) and from namespace
    dictionary of the class. Fields declared on model are all subclasses of the
    BaseField class.

    Trigger conversion of ormar field into pydantic FieldInfo, which has all needed
    parameters saved.

    Overwrites the annotations of ormar fields to corresponding types declared on
    ormar fields (constructed dynamically for relations).
    Those annotations are later used by pydantic to construct it's own fields.

    :param attrs: current class namespace
    :type attrs: dict
    :return: namespace of the class updated, dict of extracted model_fields
    :rtype: tuple[dict, dict]
    """
    model_fields = {}
    potential_fields = {}

    potential_fields.update(get_potential_fields(attrs))
    for field_name, field in potential_fields.items():
        field.name = field_name
        model_fields[field_name] = field
        default_type = (
            field.__type__ if not field.nullable else Optional[field.__type__]
        )
        overwrite_type = (
            field.__pydantic_type__
            if field.__type__ != field.__pydantic_type__
            else None
        )
        attrs["__annotations__"][field_name] = overwrite_type or default_type
    return attrs, model_fields