如果有效负载中不存在字段,pydantic 2的字段验证器不起作用

0 投票
1 回答
39 浏览
提问于 2025-04-13 16:18

我正在把我的代码从Pydantic v1迁移到Pydantic v2。以下是我在v1中的代码 -

class Destination(BaseModel):
    destination_type: DestinationType
    topic: Optional[str] = None
    request: RequestType = None
    endpoint: Optional[str] = None

    @validator("endpoint", pre=True, always=True)
    def check_endpoint(cls, value, values):
        # coding logic

以下是v2中的代码 -

class Destination(BaseModel):
    destination_type: DestinationType
    topic: Optional[str] = None
    request: RequestType = None
    endpoint: Optional[str] = None

    @field_validator("endpoint", mode='before')
    @classmethod
    def check_endpoint(cls, value, info: ValidationInfo):
        # coding logic

在我的系统运行v1的时候,不管请求中有没有endpoint这个字段,check_endpoint方法都会被执行。但是在v2中,check_endpoint方法只有在请求中有这个字段时才会执行。我该如何修改v2中的代码,让它的行为和之前完全一样呢?

1 个回答

0

你应该在你的 Destination 模型中添加 model_config = ConfigDict(validate_default=True) 这一行代码。

class Destination(BaseModel):
    ...
  
    model_config = ConfigDict(validate_default=True)  # <----- here

    @field_validator("endpoint", mode='before')
    @classmethod
    def check_endpoint(cls, value, info: ValidationInfo):
        # coding logic

撰写回答