大佬们请教个问题,pydantic库validator方法 values这个参数不是只有验证通过字段才会加进去吗,为什么这个password1在第一个执行的验证方法username_alphanumeric执行前没验证过,在这里面打印values也能取到password1的值呢
from pydantic import BaseModel, ValidationError, validator class UserModel(BaseModel): password1: str username: str password2: str name: str @validator('name') def name_must_contain_space(cls, v,values): print(values,'name') if ' ' not in v: raise ValueError('must contain a space') # print(v.title()) return v.title() @validator('password2') def passwords_match(cls, v, values): print(values,'password2') if 'password1' in values and v != values['password1']: raise ValueError('passwords do not match') return v @validator('username') def username_alphanumeric(cls, v,values): print(values,'username') assert v.isalnum(), 'must be alphanumeric' return v user = UserModel( name='samuel colvin', username='scolvin', password1='zxcvbn', password2='zxcvbn', )
执行结果
{'password1': 'zxcvbn'} username {'password1': 'zxcvbn', 'username': 'scolvin'} password2 {'password1': 'zxcvbn', 'username': 'scolvin', 'password2': 'zxcvbn'} name
群里大佬解答了,目前执行看来是pydantic对没有用validator方法验证的字段 根据 字段定义顺序 执行时pydantic默认验证字段了,通过的值也和validator方法一样 添加到values里了,,这里可以更改下 password的顺序执行代码 来调试代码看他的执行结果,