I want to dynamically generate a Pydantic model at runtime. I can do this by calling create_model. For example,
from pydantic import create_model
create_model("MyModel", i=(int,...), s=(str...))
does this same thing as
from pydantic import BaseModel
class MyModel(BaseModel):
i: int
s: str
I want to serialize these Pydantic schemas as JSON. It's easy to write code to parse JSON into create_model
arguments, and it would make sense to use the output of BaseModel.schema_json()
since that already defines a serialization format. That makes me think that there should already be some sort of BaseModel.from_json_schema
classmethod that could dynamically create a model like so
from pydantic import BaseModel
class MyModel(BaseModel):
i: int
s: str
my_model = BaseModel.from_json_schema(MyModel.schema_json())
my_model(i=5, s="s") # returns MyModel(i=5, s="s")
I can't find any such function in the documentation. Am I overlooking something, or do I have to write my own own JSON schema deserialization code?