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

fix: validation with a BaseModel field and a custom root type #2451

Merged
merged 1 commit into from Mar 3, 2021
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/2449-PrettyWood.md
@@ -0,0 +1 @@
fix validation with a `BaseModel` field and a custom root type
5 changes: 3 additions & 2 deletions pydantic/main.py
Expand Up @@ -717,11 +717,12 @@ def __get_validators__(cls) -> 'CallableGenerator':

@classmethod
def validate(cls: Type['Model'], value: Any) -> 'Model':
if isinstance(value, cls):
return value.copy() if cls.__config__.copy_on_model_validation else value

value = cls._enforce_dict_if_root(value)
if isinstance(value, dict):
return cls(**value)
elif isinstance(value, cls):
return value.copy() if cls.__config__.copy_on_model_validation else value
elif cls.__config__.orm_mode:
return cls.from_orm(value)
else:
Expand Down
11 changes: 11 additions & 0 deletions tests/test_main.py
Expand Up @@ -1137,6 +1137,17 @@ class MyModel(BaseModel):
assert m.__root__ == ['a']


def test_root_nested():
class MyList(BaseModel):
__root__: List[str]

class MyModel(BaseModel):
my_list: MyList

my_list = MyList(__root__=['pika'])
assert MyModel(my_list=my_list).dict() == {'my_list': ['pika']}


def test_encode_nested_root():
house_dict = {'pets': ['dog', 'cats']}

Expand Down