Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

squash internal __root__ models in .dict() #1607

Merged
merged 2 commits into from Jun 27, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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 @@ -606,14 +606,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 @@ -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'):

Expand Down