skip to content

V1 to V2 Migration

Pydantic 2 renamed most of the API and tightened coercion: validators, Config, parse_obj, dict() and __root__ all changed. Asked how to migrate a codebase and what the pydantic.v1 shim buys.

on this pageshow

explore

questions

6

In Pydantic 2, what replaced the version 1 model methods parse_obj, parse_raw, dict, json and from_orm, and do the old names still work?

level: juniorimportance: must knowfreq 70%

answer

  1. one prefix on every method
  2. validate in, dump out
  3. JSON input has its own method
  4. ORM reading became a config flag
  5. shims that warn until version 3

basics

~10 s

Pydantic 2 put the model API under a model_ prefix: parse_obj became model_validate, parse_raw model_validate_json, dict and json model_dump and model_dump_json, and from_orm model_validate with from_attributes. Old names remain as warning shims.

solid answer

~30 s

Pydantic 2 renamed the public `BaseModel` methods so each starts with `model_`: `parse_obj()` became `model_validate()`, `parse_raw()` became `model_validate_json()`, `dict()` became `model_dump()`, `json()` became `model_dump_json()`, `copy()` became `model_copy()`, `construct()` became `model_construct()`, `schema()` became `model_json_schema()` and `update_forward_refs()` became `model_rebuild()`. `from_orm()` folds into `model_validate()` once the model sets `from_attributes=True`. The old names survive as shims that delegate to the new ones and emit `PydanticDeprecatedSince20`, whose message says they go in version 3. Two shims in particular are not drop-in: `from_orm()` raises unless `from_attributes` is set, and `json()` raises `TypeError` for `encoder`, `models_as_dict` or any `json.dumps` keyword such as `indent`.

code

python · 27 lines
python
from pydantic import BaseModel, ConfigDict


class ProductOut(BaseModel):
    model_config = ConfigDict(from_attributes=True)

    sku: str
    price: int


class ProductRow:  # stands in for an ORM object
    sku = 'A-1'
    price = 500


from_dict = ProductOut.model_validate({'sku': 'A-1', 'price': '500'})
from_json = ProductOut.model_validate_json('{"sku": "A-1", "price": 500}')
from_row = ProductOut.model_validate(ProductRow())

print(from_dict == from_json == from_row)
#> True
print(from_row.model_dump())
#> {'sku': 'A-1', 'price': 500}
print(from_row.model_dump_json())
#> {"sku":"A-1","price":500}
print(from_row.model_copy(update={'price': 450}))
#> sku='A-1' price=450

go deeper

for a junior

Recall the pairs: model_validate and model_validate_json bring data in, model_dump and model_dump_json take it out, and model_copy and model_fields replace copy and fields.

for a middle

Explain that the version 1 names are delegating shims that warn, and name two that are not drop-in: from_orm needs from_attributes, and json rejects encoder and json.dumps keywords.

for a senior

Show how you would prove no old call is left: make PydanticDeprecatedSince20 an error in tests, because Python hides DeprecationWarning outside the main module by default.

for a principal

Weigh leaving shims in place against a sweeping rename: they work on every 2.x release, but each is a removal waiting for version 3 and noise that hides newer warnings.

## Why every method moved Pydantic 2 (released 2023-06-30) rebuilt the library on a new validation core and renamed the public surface of **`BaseModel`** on the way. Every non-deprecated model method now has a name that matches either `model_*` or `__*pydantic*__`. The version 1 names were kept where possible so that old code keeps running during a migration, but they are **deprecated shims**, not a second supported API. ## The rename table | Version 1 | Pydantic 2 | What it does | |---|---|---| | `parse_obj(data)` | `model_validate(data)` | validate Python data (a dict, or an object) | | `parse_raw(text)` | `model_validate_json(text)` | parse and validate JSON in one step | | `from_orm(obj)` | `model_validate(obj)` with `from_attributes=True` | read fields from object attributes | | `dict()` | `model_dump()` | instance to a Python dict | | `json()` | `model_dump_json()` | instance to a JSON string | | `copy()` | `model_copy()` | shallow or deep copy, with `update=` | | `construct()` | `model_construct()` | build without validation | | `schema()` | `model_json_schema()` | JSON Schema for the model | | `update_forward_refs()` | `model_rebuild()` | resolve forward references | | `__fields__` | `model_fields` | field metadata | `parse_file()` has no one-to-one successor: read the file yourself, then pass the text to `model_validate_json()` or the loaded data to `model_validate()`. ## What the old names do now - **They delegate.** `dict()` calls `model_dump()` with the same `include`, `exclude`, `by_alias` and `exclude_*` arguments; `parse_obj()` calls `model_validate()`. - **They warn.** Each call emits **`PydanticDeprecatedSince20`**, a subclass of Python's `DeprecationWarning`, with the text "Deprecated in Pydantic V2.0 to be removed in V3.0". - **The warning is easy to miss.** Python's default filters hide `DeprecationWarning` outside the `__main__` module, so a service can call `.dict()` thousands of times a minute and log nothing. - **`from_orm()` is stricter.** It raises `PydanticUserError` ("You must set the config attribute `from_attributes=True` to use from_orm") when the model does not set `from_attributes`. - **`json()` lost arguments.** `encoder` and `models_as_dict` raise `TypeError` (use field or model serializers instead), and so does any extra `json.dumps` keyword such as `indent` or `ensure_ascii`. `model_dump_json(indent=2)` takes `indent` directly. ## Reading ORM objects Version 1 needed `orm_mode = True` plus `from_orm()`. Pydantic 2 has one entry point, `model_validate()`, and one switch, `from_attributes`. Set it on the model with `model_config = ConfigDict(from_attributes=True)`, or per call with `model_validate(obj, from_attributes=True)`. With the switch on, `model_validate()` reads `obj.sku` and `obj.price` instead of expecting a dict. ## Output that changed under the new names A rename is not always a pure rename. Two output differences catch teams that compare JSON as text: - **Compact JSON.** `model_dump_json()` writes `{"a":["fancy","sushi"]}` with no spaces, where version 1's `json()` wrote `{"a": ["fancy", "sushi"]}`. Snapshot tests and signatures computed over the string change. - **Non-string dict keys** are serialized with `str(key)`, so a `None` key becomes `"None"` where version 1 wrote `"null"`. ## Neighbours that moved too - Module helpers `parse_obj_as()` and `schema_of()` are deprecated; **`TypeAdapter`** replaces them, with `validate_python()`, `validate_json()` and `json_schema()`. - `@validate_arguments` became **`@validate_call`**. - `BaseSettings` left the package for the separate **pydantic-settings** distribution. - `pydantic.generics.GenericModel` is gone: a generic model is `class Page(BaseModel, Generic[T])`. ## Migrating the call sites 1. Make the deprecation fatal in the test suite, for example `warnings.filterwarnings('error', category=PydanticDeprecatedSince20)`, so that every remaining old call fails a test instead of hiding. 2. Rename call sites using the table above; a code-transformation tool can do much of this mechanically. 3. Replace `from_orm()` with `model_validate()` and move `orm_mode` to `from_attributes` in the same change, since the old config key is not translated. 4. Rewrite every `json(...)` call that passes `json.dumps` keywords or `encoder`, because those raise rather than warn. The shims keep working on every 2.x release, so step 2 can be spread out; the warning-as-error filter is what proves it finished.

  • How do you find every remaining call to a deprecated version 1 method before Pydantic 3 removes them?
    Turn the warning into an error in tests: `warnings.filterwarnings('error', category=PydanticDeprecatedSince20)` makes each shimmed call fail the test that reaches it. A text search finds the obvious `.dict(` and `.parse_obj(` calls, but the warning also catches calls made through helpers. Its limit is coverage: a path no test exercises still only warns, silently, in production.
  • What replaces parse_file in Pydantic 2?
    Nothing one-to-one: `parse_file()` is deprecated. Read the file yourself, then call `model_validate_json()` on the text if it is JSON, or load it with whatever parser fits and pass the result to `model_validate()`. Keeping file handling out of the model also makes the validation step easy to test with plain strings.

  • parse_obj and dict() were removed in Pydantic 2, so old calls crash at once
  • from_orm still works on any Pydantic 2 model and only prints a warning
  • model_validate parses a JSON string the way parse_raw did
  • Deprecation warnings always reach the logs, so leftover old calls are easy to spot
  • json(indent=2) behaves the same in Pydantic 2 as in version 1

Assumes Pydantic 2 (checked on 2.14.0): the model_ names arrived in 2.0, and the version 1 names are deprecated shims slated for removal in version 3.

open as a page

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?

level: middleimportance: must knowfreq 66%

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.

open as a page

In Pydantic 2, how do you replace a version 1 model whose only field was __root__ holding a list, and what changes for its callers?

level: middleimportance: should knowfreq 25%

basics

~10 s

Subclass RootModel[list[Item]]: the value moves from root to .root, and validation and dumping take and return the bare list. A field named root now fails at class definition; TypeAdapter(list[Item]) suits lists needing no class.

open as a page

After a Pydantic 1 codebase moves to Pydantic 2 and every renamed API is fixed, which validation behaviours still change with no code change, and how do you catch them?

level: seniorimportance: should knowfreq 48%

basics

~20 s

Optional fields without a default become required, numbers no longer coerce to str, floats with a fraction no longer truncate to int, int | str keeps '1' a string, and pairs stop becoming dicts. Replaying real payloads through both versions catches them.

open as a page

In Pydantic 2, what does importing BaseModel from the pydantic.v1 namespace buy a team mid-migration, and where does that shim stop helping?

level: seniorimportance: should knowfreq 35%

basics

~20 s

pydantic.v1 is a copy of the version 1 library bundled inside Pydantic 2, so unmigrated models keep version 1 behaviour on the new install. It stops at the boundary: version 1 and version 2 models must not be nested or mixed.

open as a page

As the lead of a large Pydantic 1 codebase, how would you plan its move to Pydantic 2, and what would you refuse to do in a single step?

level: principalimportance: should knowfreq 32%

basics

~20 s

Stage it: switch imports to pydantic.v1 while still on version 1, upgrade the package with no behaviour change, then migrate clusters of linked models one at a time with bump-pydantic and payload-diff tests. Never upgrade and change behaviour in one step.

open as a page