Skip to content

[BUG] ValidationError not raised when validating a Pydantic model (with a missing required field) #6901

@marielejeune

Description

@marielejeune

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

Validating a Pydantic model directly using the model object does not work as expected: no ValidationError when a required field is missing.

See the two following examples, using model_validate and TypeAdapter.

See Pull Request with changes suggestions and tests : #6902

Example Code

# 1. `model_construct` then `model_validate`

from pydantic import BaseModel

class Model(BaseModel):
    x: str


obj = Model()  # ValidationError is raised: required field is missing (as expected)
obj = Model.model_construct()
obj.model_validate(obj, from_attributes=True)  # ValidationError should be raised but is not


# 2. `TypeAdapter`


from pydantic import TypeAdapter

class Model(BaseModel):
    x: str

validator = TypeAdapter(Model)
validator.validate_python({})   # ValidationError is raised: required field is missing (as expected)
m = Model.model_construct()
validator.validate_python(m, from_attributes=True) # ValidationError should be raised but is not

Python, Pydantic & OS Version

pydantic version: 2.1.1
        pydantic-core version: 2.4.0
          pydantic-core build: profile=release pgo=true mimalloc=true
                 install path: /home/marie/Projects/pydantic/pydantic
               python version: 3.10.12 (main, Jun  7 2023, 12:45:35) [GCC 9.4.0]
                     platform: Linux-5.15.0-78-generic-x86_64-with-glibc2.31
     optional deps. installed: ['devtools', 'email-validator', 'typing-extensions']

Selected Assignee: @Kludex

Metadata

Metadata

Assignees

Labels

bug V2Bug related to Pydantic V2pendingIs unconfirmed

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions