If field not present in payload, field_validator is not working for pydantic 2

41 Views Asked by At

I am migrating my code from Pydantic v1 to Pydantic v2. Following is my code in 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

Following is the code in 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

When my system was running in v1, whether the field endpoint was present in the request payload or not, the check_endpoint method was executed regardless. However, in v2, the check_endpoint method only executes if the field is present in the payload. How do I modify the code in v2 so that it behaves exactly how it behaved before?

1

There are 1 best solutions below

0
Max On

You should add model_config = ConfigDict(validate_default=True) to your Destination model

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