Serialization with model_dump()
You've validated data into a model. Now you need to send it somewhere - an API response, a file, a database. Serialization converts the model back to basic types.
user = User(name="Alice", age=30)
# To dictionary
data = user.model_dump()
print(data) # {'name': 'Alice', 'age': 30}
# To JSON string
json_str = user.model_dump_json()
print(json_str) # '{"name":"Alice","age":30}'
Control what gets included:
# Only specific fields
user.model_dump(include={"name"})
# Exclude fields
user.model_dump(exclude={"age"})
# Skip None values
user.model_dump(exclude_none=True)
For APIs, model_dump_json() is common. It handles nested models, dates, and other types automatically.
I cover serialization options in my Pydantic course.