@deprecated('Pydantic V1 style `@validator` validators are deprecated.'
' You should migrate to Pydantic V2 style `@field_validator` validators,'
' see the migration guide for more details', category=None)
def validator(__field: str,
*fields: str,
pre: bool = False,
each_item: bool = False,
always: bool = False,
check_fields: bool | None = None,
allow_reuse: bool = False) -> (_V1ValidatorType) -> _V1ValidatorType
Decorate methods on the class indicating that they should be used to validate fields.
形参:
__field – The first field the validator should be called on; this is separate from fields to ensure an error is raised if you don't pass at least one.
fields – Additional field(s) the validator should be called on.
pre – Whether this validator should be called before the standard validators (else after). Defaults to False.
each_item – For complex objects (sets, lists etc.) whether to validate individual elements rather than the whole object. Defaults to False.
always – Whether this method and other validators should be called even if the value is missing. Defaults to False.
check_fields – Whether to check that the fields actually exist on the model. Defaults to None.
allow_reuse – Whether to track and raise an error if another validator refers to the decorated function. Defaults to False.
返回值:
A decorator that can be used to decorate a function to be used as a validator.
⸻
- 警告的核心意思
在 Pydantic V1 中,我们习惯写验证器时用的是 @validator 装饰器,例如:
from pydantic import BaseModel, validator
class User(BaseModel):
name: str
@validator("name")
def name_must_not_be_blank(cls, v):
if not v.strip():
raise ValueError("Name cannot be blank")
return v
但是 在 Pydantic V2 中,这种写法已经被标记为 deprecated(弃用),会抛出你看到的这个警告。
在 V2 里,官方推荐用 @field_validator,写法变成:
from pydantic import BaseModel, field_validator
class User(BaseModel):
name: str
@field_validator("name")
@classmethod
def name_must_not_be_blank(cls, v):
if not v.strip():
raise ValueError("Name cannot be blank")
return v
⸻
- 为什么要改?
• V1 的 @validator:参数设计比较复杂(pre, each_item, always, check_fields 等),有时容易混淆。
• V2 的 @field_validator:API 更清晰,和 @model_validator(整体验证器)区分开了。
• 这样一来,维护和迁移时更直观,也符合 Pydantic V2 的整体设计。
⸻
- 警告的具体含义
• @deprecated(…):告诉你 旧的 @validator 还能用,但不推荐继续使用。
• 建议你按照 迁移指南 把代码里的 @validator 全部替换为 @field_validator。
• 将来某个版本里,@validator 可能会被彻底移除。
⸻
✅ 总结:
这个警告就是在提醒你:你正在用 Pydantic V1 风格的 @validator,请改用 V2 的 @field_validator。
1084

被折叠的 条评论
为什么被折叠?



