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?
You should add
model_config = ConfigDict(validate_default=True)to yourDestinationmodel