8000 Pydantic 1.6 does not validate nested models when using a default_factory · Issue #1710 · pydantic/pydantic · GitHub
[go: up one dir, main page]

Skip to content

Pydantic 1.6 does not validate nested models when using a default_factory #1710

@jlowin

Description

@jlowin

Bug

Output of python -c "import pydantic.utils; print(pydantic.utils.version_info())":

             pydantic version: 1.6
            pydantic compiled: True
                 install path: /usr/local/Caskroom/miniconda/base/envs/server/lib/python3.8/site-packages/pydantic
               python version: 3.8.3 (default, Jul  2 2020, 11:26:31)  [Clang 10.0.0 ]
                     platform: macOS-10.15.5-x86_64-i386-64bit
     optional deps. installed: ['typing-extensions']

I'm aware that validation does not apply to default values, but it appears that it is no longer applied to user-provided values that have a default factory value, either. If this is expected, I'm not sure if I saw it in the documentation or changelog.

from pydantic import BaseModel, Field
from typing import List

class Child(BaseModel):
    x: int

class Parent(BaseModel):
    children: List[Child] = Field(default_factory=list)


p = Parent(children=[{'x':1}, {'y':2}])

In Pydantic 1.5.1, an error is raised because the second child fails to validate (it is missing required value 'x')

In Pydantic 1.6, the Parent object is instantiated successfully and contains two dicts:

print(p)
# children=[{'x': 1}, {'y': 2}]

To avoid this and recover the expected behavior, validate_all must be set on the Parent class. However, since I'm providing the child value, I'm surprised that I had to ask for it to be validated.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug V1Bug related to Pydantic V1.X

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0