When a Pydantic 1 model moves to Pydantic 2, how do @validator, @root_validator, class Config and orm_mode translate, and what breaks if they stay?
answer
- two new decorator names
- pre becomes a mode
- values becomes info.data
- the Config class becomes a dict
- an old config key only warns
basics
~10 s@validator becomes @field_validator, with pre=True as mode='before'; @root_validator becomes @model_validator; class Config becomes model_config = ConfigDict(...); orm_mode becomes from_attributes. Leftover decorators warn or fail at import; a leftover orm_mode is ignored after a warning.
solid answer
~40 sIn Pydantic 2, `@validator` maps to `@field_validator`: `pre=True` becomes `mode='before'`, the default is `mode='after'`, the `values` argument becomes `info.data` on a `ValidationInfo`, and `each_item=True` is gone, so an item rule moves onto the item type. `@root_validator` maps to `@model_validator`; in `mode='after'` it receives the built instance and returns `self`, not a dict. `class Config` becomes `model_config = ConfigDict(...)` with renamed keys: `orm_mode` to `from_attributes`, `anystr_strip_whitespace` to `str_strip_whitespace`, `validate_all` to `validate_default`, `allow_population_by_field_name` to `validate_by_name` (2.11 and later). What breaks if they stay: the old decorators mostly still run with a deprecation warning (a `@root_validator` without `skip_on_failure=True` fails at class definition), but a renamed key such as `orm_mode` only raises a `UserWarning` and is not translated, so ORM reads fail validation.
code
python · 42 linesfrom typing import Any
from pydantic import BaseModel, ConfigDict, ValidationError, field_validator, model_validator
class ProductIn(BaseModel):
model_config = ConfigDict(str_strip_whitespace=True)
sku: str
min_price: int
max_price: int
# was: @validator('sku', pre=True)
@field_validator('sku', mode='before')
@classmethod
def normalise_sku(cls, value: Any) -> Any:
return value.upper() if isinstance(value, str) else value
# was: @root_validator(skip_on_failure=True) returning values
@model_validator(mode='after')
def check_price_range(self) -> 'ProductIn':
if self.min_price > self.max_price:
raise ValueError('min_price must not exceed max_price')
return self
class ProductOut(BaseModel):
# was: class Config: orm_mode = True
model_config = ConfigDict(from_attributes=True)
sku: str
price: int
print(ProductIn(sku=' a-1 ', min_price=100, max_price=500))
#> sku='A-1' min_price=100 max_price=500
try:
ProductIn(sku='a-1', min_price=500, max_price=100)
except ValidationError as exc:
print(exc.errors()[0]['msg'])
#> Value error, min_price must not exceed max_pricego deeper
Recall the four translations: field_validator for validator, model_validator for root_validator, model_config with ConfigDict for class Config, and from_attributes for orm_mode.
Explain the shape changes: modes replace pre, info.data replaces values, an after model validator works on the instance, and each_item moves onto the item type.
Point to the failure that ships: a leftover orm_mode only warns at import and breaks ORM reads at run time, so make Pydantic warnings fatal in tests.
Decide whether to convert validators file by file or model by model; the config-both error and deprecation noise favour finishing each model completely in one change.
## The decorator mapping Pydantic 2 deprecated both version 1 validator decorators and replaced them with two new ones whose behaviour is chosen by a **mode** instead of boolean flags. | Version 1 | Pydantic 2 | |---|---| | `@validator('sku')` | `@field_validator('sku')` (default `mode='after'`) | | `@validator('sku', pre=True)` | `@field_validator('sku', mode='before')` | | `@validator('tags', each_item=True)` | an `Annotated` rule on the item type | | `@validator('sku', always=True)` | `Field(validate_default=True)` on the field | | `values` parameter | `info.data` on `ValidationInfo` | | `field` or `config` parameter | `info.field_name` and `info.config` | | `@root_validator(pre=True)` | `@model_validator(mode='before')` | | `@root_validator(skip_on_failure=True)` | `@model_validator(mode='after')` | Two shapes change, not just names: - An **after-mode model validator** receives the validated **model instance** and returns it. A version 1 post root validator received a `values` dict and returned a dict. - **`each_item`** has no Pydantic 2 equivalent. A per-item rule goes on the item type, for example `list[Annotated[str, AfterValidator(normalise)]]` or `list[Annotated[int, Field(ge=0)]]`. Relatedly, `Field` constraints on a container are no longer pushed down to its items. ## What the old decorators do in Pydantic 2 The old decorators live on under `pydantic.deprecated` and are still importable from `pydantic`, but they are not a free pass: - Each use emits `PydanticDeprecatedSince20` at class definition. - `@root_validator` with the default `pre=False` must now pass `skip_on_failure=True`; without it the class definition raises `PydanticUserError` (code `root-validator-pre-skip`). - A `@validator` function that declares a `field` or `config` parameter raises `PydanticUserError` at class definition; those values are now on `ValidationInfo`. - `always=True` now also runs the **standard** validation of the annotated type on the default, so a mistyped default such as `x: str = 1` fails. - A `TypeError` raised inside any validator is no longer wrapped into a `ValidationError`; it propagates as a bug. ## Config: from a class to a dict Pydantic 2 reads configuration from a class attribute, `model_config`, holding a `ConfigDict`. A nested `class Config` still works but emits `PydanticDeprecatedSince20`, and declaring both on one model raises `PydanticUserError` (code `config-both`), so a half-migrated model cannot carry both. `model_config` is inherited by subclasses. Ten keys were renamed and ten removed. The renames that matter most: - `orm_mode` to `from_attributes` - `allow_population_by_field_name` to `populate_by_name`, or `validate_by_name` from 2.11 - `anystr_strip_whitespace`, `anystr_lower`, `anystr_upper` to `str_strip_whitespace`, `str_to_lower`, `str_to_upper` - `min_anystr_length`, `max_anystr_length` to `str_min_length`, `str_max_length` - `schema_extra` to `json_schema_extra`, `validate_all` to `validate_default` Removed keys include `allow_mutation` (use `frozen`), `smart_union` (smart unions are now the default), `getter_dict`, `json_loads`, `json_dumps` and `underscore_attrs_are_private`. ## The orm_mode trap A renamed or removed key is **not translated**. Pydantic 2 emits one `UserWarning` ("Valid config keys have changed in V2: 'orm_mode' has been renamed to 'from_attributes'") and then ignores the key. The model defines fine, imports fine, and fails only when an ORM object reaches it: 1. `model_validate(row)` fails with a `model_type` error, because without `from_attributes` the model expects a dict or an instance. 2. `from_orm(row)` raises `PydanticUserError`, because the shim checks the same flag. 3. The fix is one line, `model_config = ConfigDict(from_attributes=True)`, or `from_attributes=True` on the individual `model_validate()` call. ## Before and after The version 1 shape of the catalog input model, for comparison with the migrated code example: ```python from pydantic import BaseModel, root_validator, validator # version 1 class ProductIn(BaseModel): sku: str min_price: int max_price: int class Config: anystr_strip_whitespace = True @validator('sku', pre=True) def normalise_sku(cls, value): return value.upper() @root_validator(skip_on_failure=True) def check_price_range(cls, values): if values['min_price'] > values['max_price']: raise ValueError('min_price must not exceed max_price') return values ``` Field metadata that a version 1 validator read from its `field` argument (a `ModelField`, which no longer exists) is now reached through `cls.model_fields[info.field_name]`, and the config through `info.config`. ## Migrating one model 1. Replace `class Config` with `model_config = ConfigDict(...)`, renaming every key. 2. Convert each `@validator` to `@field_validator`, choosing the mode and moving `values` reads to `info.data`. 3. Convert each `@root_validator` to `@model_validator`, rewriting dict access as attribute access in after mode. 4. Run the model's tests with Pydantic warnings made fatal, so a leftover key or decorator shows up as a failure.
- Why does a root_validator that worked in version 1 raise at import time under Pydantic 2?A version 1 `@root_validator` defaults to `pre=False` and `skip_on_failure=False`, and Pydantic 2's rewritten validation no longer supports running a post root validator after field failures. The deprecated shim therefore raises `PydanticUserError` at class definition unless you pass `skip_on_failure=True`. The real fix is `@model_validator(mode='after')`, which runs only after every field has validated.
- Where did each_item=True go in Pydantic 2?`@field_validator` has no `each_item`. Put the rule on the item type instead, such as `list[Annotated[str, AfterValidator(normalise)]]` or `list[Annotated[int, Field(ge=0)]]`. The same move fixes a related change: `Field` constraints on a container are no longer pushed down to its items, so `list[str] = Field(pattern=...)` no longer checks each string.
- Pydantic 2 quietly translates orm_mode into from_attributes for you
- A field validator still receives the earlier fields as a values argument
- An after-mode model validator gets a dict of values and must return it
- You can keep class Config and add model_config beside it during migration
- each_item=True still works on @field_validator
- Raising TypeError in a validator still produces a ValidationError
Assumes Pydantic 2 (checked on 2.14.0): field_validator, model_validator and ConfigDict replaced the version 1 decorators and Config class in 2.0; validate_by_name arrived in 2.11.