Home > Mobile >  Pydantic model dynamic field type
Pydantic model dynamic field type

Time:08-20

In my current FastAPI project work, I have following scenario

from pydantic import BaseModel

class DataSchemaModel(BaseModel):
    Data: Any

I will know the Data:(Any) type during runtime(might be some other class type), not during declaration. Is it possible to implement this in pydantic model? Any suggestion is much appreciated.

CodePudding user response:

You can use pydantic's create_model to create the class with a parameterized type. Simple example to create a class where Data is typed as int:

from pydantic import create_model

# define your type or class here
data_type = int

DataSchemaModel = create_model('DataSchemaModel', Data=(data_type, ...))

# testing: works
DataSchemaModel(Data=42)

# testing: fails with 
# pydantic.error_wrappers.ValidationError: 1 validation error for  DataSchemaModel
# Data
#  value is not a valid integer (type=type_error.integer)
DataSchemaModel(Data=[1, 2])
  • Related