squash internal __root__ models in .dict() (#1607)

fix #1414

* flatten internal __root__ models

* add 1414 changes doc
This commit is contained in:
Patrick Wang
2020-06-27 09:55:17 -04:00
committed by GitHub
parent 113921c6c5
commit 5a2d78765a
3 changed files with 25 additions and 1 deletions
+1
View File
@@ -0,0 +1 @@
Squash internal `__root__` dicts in `.dict()` (and, by extension, in `.json()`).
+4 -1
View File
@@ -610,7 +610,7 @@ class BaseModel(Representation, metaclass=ModelMetaclass):
if isinstance(v, BaseModel):
if to_dict:
return v.dict(
v_dict = v.dict(
by_alias=by_alias,
exclude_unset=exclude_unset,
exclude_defaults=exclude_defaults,
@@ -618,6 +618,9 @@ class BaseModel(Representation, metaclass=ModelMetaclass):
exclude=exclude,
exclude_none=exclude_none,
)
if '__root__' in v_dict:
return v_dict['__root__']
return v_dict
else:
return v.copy(include=include, exclude=exclude)
+20
View File
@@ -869,6 +869,26 @@ def test_root_list():
assert m.__root__ == ['a']
def test_encode_nested_root():
house_dict = {'pets': ['dog', 'cats']}
class Pets(BaseModel):
__root__: List[str]
class House(BaseModel):
pets: Pets
assert House(**house_dict).dict() == house_dict
class PetsDeep(BaseModel):
__root__: Pets
class HouseDeep(BaseModel):
pets: PetsDeep
assert HouseDeep(**house_dict).dict() == house_dict
def test_root_failed():
with pytest.raises(ValueError, match='__root__ cannot be mixed with other fields'):