I have 2 models, 1 subclassing the other:
from pydantic import BaseModel
from typing import List
class Model1(BaseModel):
names: List[str]
class Model2(Model1):
# define here an alias for names -> e.g. "firstnames"
pass
data = { "names": ["rodrigo", "julien", "matthew", "bob"] }
# Model1(**data).dict() -> gives {'names': ['rodrigo', 'julien', 'matthew', 'bob']}
# Model2(**data).dict() -> gives {'firstnames': ['rodrigo', 'julien', 'matthew', 'bob']}
How can I accomplish this ?
Advertisement
Answer
You don’t need to subclass to accomplish what you want (unless your need is more complex than your example).
For import: Add the Config option to allow_population_by_field_name so you can add the data with names or firstnames
For export: Add by_alias=True to the dict() method to control the output
from pydantic import BaseModel
from typing import List
class Model(BaseModel):
names: List[str] = Field(alias="firstnames")
class Config:
allow_population_by_field_name = True
def main():
data = {"names": ["rodrigo", "julien", "matthew", "bob"]}
model = Model(**data)
print(model.dict())
print(model.dict(by_alias=True))
if __name__ == '__main__':
main()
yields:
{'names': ['rodrigo', 'julien', 'matthew', 'bob']}
{'firstnames': ['rodrigo', 'julien', 'matthew', 'bob']}