29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362 | class PydanticMixin(RelationMixin):
__cache__: dict[tuple[type, str, str, str], type[pydantic.BaseModel]] = {}
if TYPE_CHECKING: # pragma: no cover
__pydantic_decorators__: DecoratorInfos
@classmethod
def get_pydantic(
cls,
*,
include: Union[set, dict, None] = None,
exclude: Union[set, dict, None] = None,
flatten_fields: Union[
set, list, str, tuple, dict, "FieldAccessor", None
] = None,
flatten_all: bool = False,
max_depth: Optional[int] = None,
omit_back_relations: Optional[bool] = None,
) -> type[pydantic.BaseModel]:
"""
Returns a pydantic model out of ormar model.
Converts also nested ormar models into pydantic models. Each related
model is generated once as a named nested model and relations point to
it, so cyclic relations give recursive models (``$ref`` in OpenAPI).
Relation fields of nested models are optional, the root model keeps
the required/optional rules of its own fields. Generated models are
cached and their names do not depend on the order of calls
(``Book``, ``Book_nested``, ``Book_depth2``, a selector hash suffix).
Can be used to fully exclude certain fields in fastapi response and requests.
Relations listed in ``flatten_fields`` (or all relations with
``flatten_all``) are represented by the related model's primary key
(or a list of primary keys for many-to-many and reverse relations)
instead of a nested pydantic model, matching the output of
``model_dump`` called with the same arguments.
:param include: fields of own and nested models to include
:type include: Union[set, dict, None]
:param exclude: fields of own and nested models to exclude
:type exclude: Union[set, dict, None]
:param flatten_fields: relations to represent as their primary key
:type flatten_fields: Union[set, list, str, tuple, dict, FieldAccessor, None]
:param flatten_all: if True every relation is represented as its pk
:type flatten_all: bool
:param max_depth: number of relation levels to nest at most, None for
no limit (cycles become recursive models)
:type max_depth: Optional[int]
:param omit_back_relations: leave the relation back to the parent out
of nested models (one nested model per (model, relation) pair),
False by default (one nested model per model)
:type omit_back_relations: Optional[bool]
:raises QueryDefinitionError: on invalid flatten paths or when a
flattened relation has sub-field include/exclude
"""
flatten_map = resolve_flatten_map(
model_cls=cast(type["Model"], cls),
flatten_fields=flatten_fields,
flatten_all=flatten_all,
)
if flatten_map is not None:
flatten_map.check_vs_selector(normalize_to_dict(include), "include")
flatten_map.check_vs_selector(normalize_to_dict(exclude), "exclude")
if (
instance_traversal_enabled()
or max_depth is not None
or omit_back_relations is not None
):
return RecursiveSchemaBuilder(
omit_back_relations=bool(omit_back_relations)
).build(
model=cls,
include=include,
exclude=exclude,
flatten_map=flatten_map,
max_depth=max_depth,
)
return cls._convert_ormar_to_pydantic(
include=include,
exclude=exclude,
flatten_map=flatten_map,
relation_map=cls._relation_tree(),
)
@classmethod
def _convert_ormar_to_pydantic(
cls,
relation_map: dict[str, Any],
include: Union[set, dict, None] = None,
exclude: Union[set, dict, None] = None,
flatten_map: Optional[FlattenMap] = None,
) -> type[pydantic.BaseModel]:
include = normalize_to_dict(include)
exclude = normalize_to_dict(exclude)
fields_dict: dict[str, Any] = dict()
defaults: dict[str, Any] = dict()
fields_to_process = filter_not_excluded_fields(
fields={*cls.ormar_config.model_fields.keys()},
include=include,
exclude=exclude,
)
fields_to_process.sort(
key=lambda x: list(cls.ormar_config.model_fields.keys()).index(x)
)
cache_key = (cls, str(include), str(exclude), str(flatten_map))
if cache_key in cls.__cache__:
return cls.__cache__[cache_key]
for name in fields_to_process:
field = cls._determine_pydantic_field_type(
name=name,
defaults=defaults,
include=include,
exclude=exclude,
flatten_map=flatten_map,
relation_map=relation_map,
)
if field is not None:
fields_dict[name] = field
model = type(
f"{cls.__name__}_{''.join(choices(string.ascii_uppercase, k=3))}",
(pydantic.BaseModel,),
{"__annotations__": fields_dict, **defaults},
)
model = cast(type[pydantic.BaseModel], model)
cls._copy_computed_fields(model=model, include=include, exclude=exclude)
cls._copy_field_validators(model=model)
cls.__cache__[cache_key] = model
return model
@classmethod
def _determine_pydantic_field_type(
cls,
name: str,
defaults: dict,
include: Union[set, dict, None],
exclude: Union[set, dict, None],
flatten_map: Optional[FlattenMap],
relation_map: dict[str, Any],
) -> Any:
field = cls.ormar_config.model_fields[name]
target: Any = None
if field.is_relation and name in relation_map:
if flatten_map and flatten_map.is_field_flattened(name):
target = cls._determine_flattened_relation_field_type(
name=name, field=field, defaults=defaults
)
else:
target = cls._determined_included_relation_field_type(
name=name,
field=field,
include=include,
exclude=exclude,
flatten_map=flatten_map.descend(name) if flatten_map else None,
defaults=defaults,
relation_map=relation_map,
)
elif not field.is_relation:
defaults[name] = cls.model_fields[name].default # type: ignore
target = field.__type__
if target is not None and field.nullable:
target = Optional[target]
return target
@classmethod
def _determined_included_relation_field_type(
cls,
name: str,
field: Union[BaseField, ForeignKeyField, ManyToManyField],
include: Union[set, dict, None],
exclude: Union[set, dict, None],
flatten_map: Optional[FlattenMap],
defaults: dict,
relation_map: dict[str, Any],
) -> Any:
target = field.to._convert_ormar_to_pydantic(
include=skip_ellipsis(include, name),
exclude=skip_ellipsis(exclude, name),
flatten_map=flatten_map,
relation_map=cast(
dict[str, Any], skip_ellipsis(relation_map, name, default=dict())
),
)
return cls._wrap_relation_field_type(
name=name, field=field, target=target, defaults=defaults
)
@classmethod
def _determine_flattened_relation_field_type(
cls,
name: str,
field: Union[BaseField, ForeignKeyField, ManyToManyField],
defaults: dict,
) -> Any:
"""
Build the pydantic type of a flattened relation: the related
model's pk type with a before-validator that reduces nested dicts and
model instances to their pk value.
:param name: name of the relation field
:type name: str
:param field: ormar relation field
:type field: Union[BaseField, ForeignKeyField, ManyToManyField]
:param defaults: default values of the generated pydantic model
:type defaults: dict
:return: pydantic annotation of the field
:rtype: Any
"""
relation_field = cast("ForeignKeyField", field)
target: Any = Annotated[
relation_field.flat_value_type(), # type: ignore
BeforeValidator(
partial(extract_pk_value, fields=relation_field.flat_fields())
),
]
return cls._wrap_relation_field_type(
name=name, field=field, target=target, defaults=defaults
)
@staticmethod
def _wrap_relation_field_type(
name: str,
field: Union[BaseField, ForeignKeyField, ManyToManyField],
target: Any,
defaults: dict,
) -> Any:
"""
Wrap relation target type in a list for multi and reverse relations and
register a ``None`` default for nullable relations.
:param name: name of the relation field
:type name: str
:param field: ormar relation field
:type field: Union[BaseField, ForeignKeyField, ManyToManyField]
:param target: pydantic type of a single related item
:type target: Any
:param defaults: default values of the generated pydantic model
:type defaults: dict
:return: pydantic annotation of the field
:rtype: Any
"""
if field.kind.many:
target = list[target] # type: ignore
if field.nullable:
defaults[name] = None
return target
@classmethod
def _copy_computed_fields(
cls,
model: type[pydantic.BaseModel],
include: Optional[dict],
exclude: Optional[dict],
) -> None:
"""
Copy ``@pydantic.computed_field`` decorated methods from the ormar model
onto the generated pydantic model so they are exposed in the schema and
serialization output. Computed fields are filtered with the same
include/exclude rules as regular fields.
:param model: pydantic model generated from the ormar model
:type model: type[pydantic.BaseModel]
:param include: fields of own and nested models to include
:type include: Optional[dict]
:param exclude: fields of own and nested models to exclude
:type exclude: Optional[dict]
"""
computed_fields = cls.__pydantic_decorators__.computed_fields
if not computed_fields:
return
names_to_copy = filter_not_excluded_fields(
fields=set(computed_fields.keys()),
include=include,
exclude=exclude,
)
for name in names_to_copy:
decorator = computed_fields[name]
setattr(model, name, decorator.info.wrapped_property)
model.__pydantic_decorators__.computed_fields[name] = copy.copy(decorator)
@classmethod
def _copy_field_validators(
cls, model: type[pydantic.BaseModel], rebuild: bool = True
) -> None:
"""
Copy field validators from ormar model to generated pydantic model.
:param model: pydantic model generated from the ormar model
:type model: type[pydantic.BaseModel]
:param rebuild: rebuild the model right away, False when its forward
references are resolved later
:type rebuild: bool
"""
filed_names = list(model.model_fields.keys())
cls.copy_selected_validators_type(
model=model, fields=filed_names, validator_type="field_validators"
)
cls.copy_selected_validators_type(
model=model, fields=filed_names, validator_type="validators"
)
class_validators = cls.__pydantic_decorators__.root_validators
model.__pydantic_decorators__.root_validators.update(
copy.deepcopy(class_validators)
)
model_validators = cls.__pydantic_decorators__.model_validators
model.__pydantic_decorators__.model_validators.update(
copy.deepcopy(model_validators)
)
if rebuild:
model.model_rebuild(force=True)
@classmethod
def copy_selected_validators_type(
cls, model: type[pydantic.BaseModel], fields: list[str], validator_type: str
) -> None:
"""
Copy field validators from ormar model to generated pydantic model.
"""
validators = getattr(cls.__pydantic_decorators__, validator_type)
for name, decorator in validators.items():
if any(field_name in decorator.info.fields for field_name in fields):
copied_decorator = copy.deepcopy(decorator)
copied_decorator.info.fields = [
field_name
for field_name in decorator.info.fields
if field_name in fields
]
getattr(model.__pydantic_decorators__, validator_type)[name] = (
copied_decorator
)
|