Skip to content

Commit

Permalink
squash internal __root__ models in .dict() (#1607)
Browse files Browse the repository at this point in the history
fix #1414

* flatten internal __root__ models

* add 1414 changes doc
  • Loading branch information
Patrick Wang committed Jun 27, 2020
1 parent 113921c commit 5a2d787
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
1 change: 1 addition & 0 deletions changes/1414-patrickkwang.md
@@ -0,0 +1 @@
Squash internal `__root__` dicts in `.dict()` (and, by extension, in `.json()`).
5 changes: 4 additions & 1 deletion pydantic/main.py
Expand Up @@ -610,14 +610,17 @@ 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,
include=include,
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)

Expand Down
20 changes: 20 additions & 0 deletions tests/test_main.py
Expand Up @@ -869,6 +869,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'):

Expand Down

0 comments on commit 5a2d787

Please sign in to comment.