Reputation: 3
I'm using fastapi to create an api, and I need to adjust the output object in pydantic but I'm not getting it. My code:
class Obj1(BaseModel):
d:str = None
e:str = None
class Obj(BaseModel):
a:int = None
b:str = None
c:Obj1 = None
data = {'a': 1, 'b': 'b', 'd': 'd', 'e':'e'}
obj = Obj(**data)
In this way, I lose the values of d and e.
Obj(a=1, b='b', c=None)
The expected value would be
Obj(a=1, b='b', c=Obj1(d='d', e='e'))
Is there any method in pydantic that I can use to make the correct transformation of the data? I tried to use root_validator to set the object's value but had errors. Tanks.
Upvotes: 0
Views: 471
Reputation: 32233
The given data
dictionary does not match the defined models, this one will match:
data = {'a': 1, 'b': 'b', 'c': {'d': 'd', 'e': 'e'}}
By default pydantic
ignores extra attributes, and you could simply do that:
obj = Obj(**data, c=Obj1(**data))
Upvotes: 1