parse_obj
- Python course
- Advanced
- Lesson 59/83
- 5 min
Learn dict-to-model with Model.parse_obj.
model_validate
In Pydantic v2, model_validate turns a dict into a model. It is the recommended replacement for the old parse_obj. It builds a model instance from a dict.
from pydantic import BaseModel
class User(BaseModel):
name: str
age: int
data = {"name": "Ayşe", "age": 30}
u = User.model_validate(data)
print(u.name) # AyşeThis method is ideal for building a model from structured data (e.g. a structured-data format). Bad data raises a validation error.
Validation and errors
model_validate validates the data and turns it into a model. If a required field is missing or a type does not match, ValidationError is raised. The error is detailed; it tells which field failed and why.
try:
u = User.model_validate({"name": "Ayşe"}) # age missing
except ValidationError as e:
print(e)For this reason, using try/except when converting data from an untrusted source is a good practice.
Practice Build a User model from a dict
Start with from pydantic import BaseModel. Define class User(BaseModel): with fields name: str and age: int. Define data = {"name": "Ayşe", "age": 30}. Build the model with u = User.model_validate(data). Print the values with print(u.name, u.age).
Starter code
# bring in BaseModel from pydantic
# define User class (name and age fields)
# define a dict called data (Ayşe, 30)
# turn the dict into a model with model_validate
# print the name and age valuesSample solution
from pydantic import BaseModel
class User(BaseModel):
name: str
age: int
data = {"name": "Ayşe", "age": 30}
u = User.model_validate(data)
print(u.name, u.age)Expected output
Ayşe 30
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the model_validate call
data = {"name": "Ayşe", "age": 30}
u = User.____(data)
data = {"name": "Ayşe", "age": 30}
u = User.model_validate(data)
Explanation: User.model_validate(data) builds a model.
2 What does User.model_validate(data) return?
- A dict
- A User instance Correct answer
- A string
- A list
Explanation: model_validate returns a User instance.
3 Match the model_validate concepts
| Term | Meaning |
|---|---|
model_validate |
Turns dict into model |
ValidationError |
Is a validation error |
data |
Is the input dict |
User instance |
Is the output |