I have 2 models, 1 subclassing the other:
JavaScript
x
14
14
1
from pydantic import BaseModel
2
from typing import List
3
4
class Model1(BaseModel):
5
names: List[str]
6
7
class Model2(Model1):
8
# define here an alias for names -> e.g. "firstnames"
9
pass
10
11
data = { "names": ["rodrigo", "julien", "matthew", "bob"] }
12
# Model1(**data).dict() -> gives {'names': ['rodrigo', 'julien', 'matthew', 'bob']}
13
# Model2(**data).dict() -> gives {'firstnames': ['rodrigo', 'julien', 'matthew', 'bob']}
14
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
JavaScript
1
21
21
1
from pydantic import BaseModel
2
from typing import List
3
4
5
class Model(BaseModel):
6
names: List[str] = Field(alias="firstnames")
7
8
class Config:
9
allow_population_by_field_name = True
10
11
12
def main():
13
data = {"names": ["rodrigo", "julien", "matthew", "bob"]}
14
model = Model(**data)
15
print(model.dict())
16
print(model.dict(by_alias=True))
17
18
19
if __name__ == '__main__':
20
main()
21
yields:
JavaScript
1
3
1
{'names': ['rodrigo', 'julien', 'matthew', 'bob']}
2
{'firstnames': ['rodrigo', 'julien', 'matthew', 'bob']}
3