V1 to V2 Migration

Pydantic 2.0, released in July 2023, rewrites the core in Rust (pydantic-core) for 5-50x performance gains. The API changes: BaseSettings, validators, and configuration are refactored.

Key Changes

python
# Pydantic V1
# from pydantic import BaseModel, validator
# class User(BaseModel):
#     name: str
#     class Config:
#         orm_mode = True
#     @validator('name')
#     def check(cls, v): ...

# Pydantic V2
from pydantic import BaseModel, field_validator, ConfigDict

class User(BaseModel):
    model_config = ConfigDict(from_attributes=True)
    name: str

    @field_validator('name')
    @classmethod
    def check(cls, v: str) -> str:
        if not v.strip():
            raise ValueError('name must not be blank')
        return v.strip()

u = User(name='  Alice  ')
print(u.name)  # 'Alice'

Sources