I need to have a variable covars
that contains an unknown number of entries, where each entry is one of three different custom Pydantic
models. In this case, each entry describes a variable for my application.
Specifically, I want covars
to have the following form. It is shown here for three entries, namely variable1
, variable2
and variable3
, representing the three different types of entries. Though, when deployed, the application must allow to receive more than three entries, and not all entry types need to be present in a request.
covars = {
'variable1': # type: integer
{
'guess': 1,
'min': 0,
'max': 2,
},
'variable2': # type: continuous
{
'guess': 12.2,
'min': -3.4,
'max': 30.8,
},
'variable3': # type: categorical
{
'guess': 'red',
'options': {'red', 'blue', 'green'},
}
}
I have successfully created the three different entry types as three separate Pydantic
models
import pydantic
from typing import Set, Dict, Union
class IntVariable(pydantic.BaseModel):
guess: int
min: int
max: int
class ContVariable(pydantic.BaseModel):
guess: float
min: float
max: float
class CatVariable(pydantic.BaseModel):
guess: str
options: Set[str] = {}
Notice the data type difference between IntVariable
and ContVariable
.
My question: How to make a Pydantic
model that allows combining any number of entries of types IntVariable
, ContVariable
and CatVariable
to get the output I am looking for?
The plan is to use this model to verify the data as it is being posted to the API, and then store a serialized version to the application db (using ormar
).