Suppose I have the following input data regarding a pet owner.
from types import SimpleNamespace
petowner1 = SimpleNamespace(
id = 1,
cats = [
SimpleNamespace(id=1, name='Princess Peach')
],
dogs = [
SimpleNamespace(id=1, name='Sparky'),
SimpleNamespace(id=2, name='Clifford')
]
)
petowner1 has an id, a list of cats, and a list of dogs. ...but I think it makes more sense for an Owner to have a list of Pets, each with a type attribute ('cat' or 'dog'). Hence, I set up the following Pydantic models
class Pet(BaseModel):
id: int
type: str
name: str
class Config:
orm_mode = True
class Owner(BaseModel):
id: int
pets: List[Pet]
class Config:
orm_mode = True
Given my input data, how can I populate these Pydantic models? My end goal is to do something like
owner = Owner.from_orm(petowner1)
owner.json()
which should output
{
'id': 1,
'pets': [
{'id': 1, 'type': 'cat', 'name': 'Princess Peach'},
{'id': 1, 'type': 'dog', 'name': 'Sparky'},
{'id': 2, 'type': 'dog', 'name': 'Clifford'}
]
}