From 20f134604c56ff046e6e017c1f3e7ee8dd0f77f0 Mon Sep 17 00:00:00 2001 From: Patrick Wang Date: Fri, 5 Jun 2020 22:11:07 -0400 Subject: [PATCH 1/2] flatten internal __root__ models --- pydantic/main.py | 5 ++++- tests/test_main.py | 20 ++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/pydantic/main.py b/pydantic/main.py index bb01d2e3cc..eb32ee3e01 100644 --- a/pydantic/main.py +++ b/pydantic/main.py @@ -606,7 +606,7 @@ def _get_value( 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, @@ -614,6 +614,9 @@ def _get_value( 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) diff --git a/tests/test_main.py b/tests/test_main.py index c70ada964e..3dca0b87aa 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -863,6 +863,26 @@ class MyModel(BaseModel): 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'): From bb22ec78b318dea5e7f85f73e807b783b99cdc2b Mon Sep 17 00:00:00 2001 From: Patrick Wang Date: Fri, 5 Jun 2020 22:25:49 -0400 Subject: [PATCH 2/2] add 1414 changes doc --- changes/1414-patrickkwang.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changes/1414-patrickkwang.md diff --git a/changes/1414-patrickkwang.md b/changes/1414-patrickkwang.md new file mode 100644 index 0000000000..898f5f8cd4 --- /dev/null +++ b/changes/1414-patrickkwang.md @@ -0,0 +1 @@ +Squash internal `__root__` dicts in `.dict()` (and, by extension, in `.json()`). \ No newline at end of file