Currently we have good Pydantic support, via the create_pydantic_model function (see docs). For example:
BandModel = create_pydantic_model(table=Band, exclude_columns=(Band.popularity,), model_name='BandModel')
We could potentially add a PydanticModel class, which performs something similar (it will likely use create_pydantic_model under the hood):
# The class will accept most of the arguments that `create_pydantic_model` does:
class BandModel(PydanticModel, table=Band, exclude_columns=(Band.popularity,)):
# We can define additional fields:
some_extra_field: int
It would require some metaclass magic to make this work.
The advantages over create_pydantic_model are:
It's easier to add additional fields to the model
With create_pydantic_model:
BandModel = create_pydantic_model(table=Band)
class BandModelExtended(BandModel):
some_extra_field: str
With PydanticModel:
class BandModelExtended(PydanticModel, table=Band):
some_extra_field: str
Less likely a name clash will occur
With create_pydantic_model, if it's used multiple times on the same table, it's important to provide the model_name argument, to prevent issues with FastAPI:
BandModel = create_pydantic_model(table=Band, model_name='BandModel')
BandModelOptional = create_pydantic_model(table=Band, optional=True, model_name='BandModelOptional')
With PydanticModel, this problem is avoided, as the model name is automatically just the class name.
class BandModel(PydanticModel, table=Band):
pass
class BandModelOptional(PydanticModel, table=Band, optional=True):
pass
Update 24/3/2022
If building a new API around Pydantic model creation, these are the other things I'd change from the current create_pydantic_model implementation:
Currently we have good Pydantic support, via the create_pydantic_model function (see docs). For example:
We could potentially add a PydanticModel class, which performs something similar (it will likely use create_pydantic_model under the hood):
It would require some metaclass magic to make this work.
The advantages over create_pydantic_model are:
It's easier to add additional fields to the model
With create_pydantic_model:
With PydanticModel:
Less likely a name clash will occur
With create_pydantic_model, if it's used multiple times on the same table, it's important to provide the model_name argument, to prevent issues with FastAPI:
With PydanticModel, this problem is avoided, as the model name is automatically just the class name.
Update 24/3/2022
If building a new API around Pydantic model creation, these are the other things I'd change from the current create_pydantic_model implementation: