Menu

The Pydantic v1 to v2 cheat sheet (and the trap the deprecation warnings hide)
📰

The Pydantic v1 to v2 cheat sheet (and the trap the deprecation warnings hide)

DEV Community: fastapi·Versyka·8 days ago
#zuLayamu
#devtofastapi#devto#dev#user#pydantic
Reading 0:00
15s threshold

Versyka

Posted on Nov 8

AI-assisted

Pydantic v2 rewrote the core in Rust and renamed a lot of the public API. Most projects hit the same handful of changes first.

The renames

- user.dict() + user.model_dump() - user.json() + user.model_dump_json() - User.parse_obj(data) + User.model_validate(data) - User.parse_raw(text) + User.model_validate_json(text)

Enter fullscreen mode

Exit fullscreen mode

Validators changed shape, not just name

- from pydantic import validator + from pydantic import field_validator class User(BaseModel): email: str - @validator("email", pre=True) - def clean(cls, v): + @field_validator("email", mode="before") + @classmethod + def clean(cls, v): return v.strip().lower()

Enter fullscreen mode

Exit fullscreen mode

pre=True is mode="before" , and the validator is an explicit classmethod.

Config moved

class User(BaseModel): - class Config: - orm_mode = True + model_config = ConfigDict(from_attributes=True)

Enter fullscreen mode

Exit fullscreen mode

Note the rename inside it…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.