Skip to content

Commit

Permalink
fix: validation with a BaseModel field and a custom root type
Browse files Browse the repository at this point in the history
  • Loading branch information
PrettyWood committed Mar 2, 2021
1 parent d619457 commit b413676
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 2 deletions.
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
12 changes: 12 additions & 0 deletions tests/test_main.py
Expand Up @@ -17,6 +17,7 @@
ValidationError,
constr,
root_validator,
validate_model,
validator,
)
from pydantic.typing import Literal
Expand Down Expand Up @@ -1137,6 +1138,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

0 comments on commit b413676

Please sign in to comment.