简体   繁体   中英

How to validate a pydantic object after editing it

Is there any obvious to validate a pydantic model after some changing some attribute?

Say I create a simple Model and object:

from pydantic import BaseModel

class A(BaseModel):
    b: int = 0

a=A()

Then edit it, so that it is actually invalid:

a.b = "foobar"

Can I force a re-validation and expect a ValidationError to be raised?

I tried

A.validate(a)                      # no error
a.copy(update=dict(b='foobar'))    # no error

What did work was

A(**dict(a._iter()))

ValidationError: 1 validation error for A
b
  value is not a valid integer (type=type_error.integer)

But that is not really straightforward and I need to use the supposedly private method _iter .

Is there a clean alternative?

pydantic can do this for you, you just need validate_assignment :

from pydantic import BaseModel

class A(BaseModel):
    b: int = 0

    class Config:
        validate_assignment = True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM