Skip to content

Instantly share code, notes, and snippets.

@socrateslee
Created December 9, 2024 15:07
Show Gist options
  • Save socrateslee/db6d2da8197fe1a15b6094eb6e3305dd to your computer and use it in GitHub Desktop.
Save socrateslee/db6d2da8197fe1a15b6094eb6e3305dd to your computer and use it in GitHub Desktop.
Create a partial model definition of a pydantic model with specified fields.
import pydantic
def partial_model(model: pydantic.BaseModel,
partial_model_name: str,
include: list[str] | None = None,
exclude: list[str] | None= None,
doc: str | None= None,
module: str | None = None
):
fields = []
for name, info in model.model_fields.items():
if exclude and name in exclude:
continue
if include and name not in include:
continue
fields.append((name, info))
new_model = pydantic.create_model(
partial_model_name,
__doc__=doc or model.__doc__,
__base__=model.__mro__[1:],
__module__=module or model.__module__,
**{name: (info.annotation, info) for (name, info) in fields}
)
for field in model.model_computed_fields:
if field in model.__dict__:
setattr(new_model, field, getattr(model, field))
new_model.__pydantic_validator__ = model.__pydantic_validator__
return new_model
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment