model_validate() call can safely parse an entire deeply nested JSON payload from an external API, raising precise errors for any field that doesn’t conform, no matter how deep it sits.
Using one model inside another
Declare a model as the type annotation for a field, just like you would withstr or int:
Parsing nested dictionaries
The real power of nested models becomes clear when you parse dictionaries — for example, a JSON payload from an HTTP request:OrderItem from the inner dictionary. If any nested field has the wrong type, you get a clear error pointing to the exact path — e.g. item.price.
Lists of nested models
Uselist[YourModel] to declare a field that holds multiple nested objects:
Optional nested models
Make a nested model optional by using| None with a default of None:
Pydantic coerces nested dictionaries into the declared model type for you. You don’t need to manually construct
Discount(...) before passing it in — a plain dict works.Deep nesting
There’s no limit to how deep you can nest models. Pydantic validates the entire tree:Serialising nested models
model_dump() converts the entire model tree to a plain dictionary, and model_dump_json() converts it to a JSON string — nested models are handled automatically:
Common patterns
Reusing a model across multiple contexts
Reusing a model across multiple contexts
Define a general-purpose model once and reference it wherever it’s needed:
Self-referencing models (tree structures)
Self-referencing models (tree structures)
A model can reference itself, which is useful for comments, categories, or any tree-shaped data:The
from __future__ import annotations import is required to allow Comment to reference itself before the class definition is complete.Summary
1
Nest a model as a field
Use any Pydantic model as the type annotation for a field in another model.
2
Parse from nested dicts
Call
Model.model_validate(data) or Model(**data) — Pydantic builds nested models from inner dictionaries automatically.3
Use list[Model] for collections
Declare
items: list[OrderItem] to validate a list of nested objects in one shot.4
Serialise the whole tree
model_dump() and model_dump_json() recursively convert all nested models to dicts/JSON.Learn more
What’s next?
You can now handle complex, deeply nested data. Next, learn how to manage your application’s configuration — API keys, ports, debug flags — with full type safety using Pydantic Settings.Pydantic Settings
Learn how to manage environment-based application configuration with Pydantic Settings.