[英]Pydantic model does not validate on assignment with reproducable code
When assigning an incorrect attribute to a Pydantic model field, no validation error occurs.将不正确的属性分配给 Pydantic model 字段时,不会发生验证错误。
from pydantic import BaseModel
class pyUser(BaseModel):
username: str
class Config:
validate_all = True
validate_assignment = True
person = pyUser(username=1234)
person.username
>>>1234
try_again = pyUser()
pydantic.error_wrappers.ValidationError:
[ErrorWrapper(exc=MissingError(), loc=('username',))]
<class '__main__.pyUser'>
How can I get pydantic to validate on assignment?如何让 pydantic 验证分配?
It is expected behaviour according to the documentation :根据文档,这是预期的行为:
str
strings are accepted as-is,
int
,float
andDecimal
are coerced usingstr(v)
字符串按原样接受,int
,float
和Decimal
使用str(v)
强制
You can use the StrictStr
, StrictInt
, StrictFloat
, and StrictBool
types to prevent coercion from compatible types.您可以使用StrictStr
、 StrictInt
、 StrictFloat
和StrictBool
类型来防止来自兼容类型的强制。
from pydantic import BaseModel, StrictStr
class pyUser(BaseModel):
username: StrictStr
class Config:
validate_all = True
validate_assignment = True
person = pyUser(username=1234) # ValidationError `str type expected`
print(person.username)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.