Create a partial model definition of a pydantic model
Sometimes I want to create a partial model definition of a pydantic model. For example, if I want to expose a database model from API, some of the fields I would like to keep in secret, or I just want to expose very few fields in a summary API. I don't want to write model definition twice. I would like to write something like
1ModelExposed = partial_model(ModelSource, 'ModelExposed', include=["title", "description"])
So I write a funciton as below to do it, including support of passing list of excluding fields, copying computed fields and validators.
1def partial_model(model: pydantic.BaseModel,
2 partial_model_name: str,
3 include: list[str] | None = None,
4 exclude: list[str] | None= None,
5 doc: str | None= None,
6 module: str | None = None
7 ):
8 fields = []
9 for name, info in model.model_fields.items():
10 if exclude and name in exclude:
11 continue
12 if include and name not in include:
13 continue
14 fields.append((name, info))
15 new_model = pydantic.create_model(
16 partial_model_name,
17 __doc__=doc or model.__doc__,
18 __base__=model.__mro__[1:],
19 __module__=module or model.__module__,
20 **{name: (info.annotation, info) for (name, info) in fields}
21 )
22 for field in model.model_computed_fields:
23 if field in model.__dict__:
24 setattr(new_model, field, getattr(model, field))
25 new_model.__pydantic_validator__ = model.__pydantic_validator__
26 return new_model