mirror of
https://github.com/kennethreitz/pydantic.git
synced 2026-06-05 23:00:18 +00:00
squash internal __root__ models in .dict() (#1607)
fix #1414 * flatten internal __root__ models * add 1414 changes doc
This commit is contained in:
@@ -0,0 +1 @@
|
||||
Squash internal `__root__` dicts in `.dict()` (and, by extension, in `.json()`).
|
||||
+4
-1
@@ -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)
|
||||
|
||||
|
||||
@@ -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'):
|
||||
|
||||
|
||||
Reference in New Issue
Block a user