简体   繁体   English

如何在编辑后验证 pydantic object

[英]How to validate a pydantic object after editing it

Is there any obvious to validate a pydantic model after some changing some attribute?在更改某些属性后,是否有任何明显的证据可以验证 pydantic model?

Say I create a simple Model and object:假设我创建了一个简单的 Model 和 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?我可以强制重新验证并期望引发ValidationError吗?

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 .但这并不是很简单我需要使用所谓的私有方法_iter

Is there a clean alternative?有干净的替代品吗?

pydantic can do this for you, you just need validate_assignment : pydantic 可以为你做到这一点,你只需要validate_assignment

from pydantic import BaseModel

class A(BaseModel):
    b: int = 0

    class Config:
        validate_assignment = True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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