Ansar Ktk
Ansar Ktk

Reputation: 147

How to fix Pydantic's deprecation warning about using model.dict() method?

When I use .dict() method on a Pydantic model in FastAPI, it gives me a deprecation warning. I upgraded pydantic through command line, but it still shows the same error. I also updated VScode, but same problem.

Upvotes: 13

Views: 21194

Answers (1)

Chris
Chris

Reputation: 34551

In Pydantic V2 model.dict() was changed to model.model_dump() (similarly, model.json() was replaced by model.model_dump_json()). You could find more details at the Migration guide and Model methods and properties, as well as the relevant documentation of the methods provided above.

Note that Pydantic models could also be converted into dictionaries using dict(model). Using that approach, the raw field values are returned, so sub-models will not be converted into dictionaries. Either model.model_dump() or dict(model) will provide a dict of fields, but model.model_dump() can take numerous other arguments—such as mode, for instance, which is useful when dealing with non-JSON serializable objects (see the relevant documentation)—as well as will recursively convert nested models into dicts.

Upvotes: 28

Related Questions