Nested Pydantic Models: Composing Complex Data

Use a Pydantic model as a field type inside another to build complex, nested structures. This is essential for modeling JSON with sub-objects, like a user with an address.
WHY IT EXISTS: Real-world data is rarely flat. APIs and configuration files often have structured, hierarchical data, like a JSON object nested inside another. Nested models provide a way to represent and validate this entire structure in your code, ensuring the whole data tree is correct, not just the top-level keys.
THE MENTAL MODEL: Think of Pydantic models as custom data types you invent. Just as you can have a list of ints, a field in one model can be another model, like a User model. You are composing data structures like Lego bricks, where each brick is a self-contained, validated unit. The parent model delegates validation for a subsection of the data to the appropriate child model.
HOW IT WORKS: You define two or more classes that inherit from BaseModel. Then, in the parent model, you declare a field and use the child model's class name as the type hint. For example, class User(BaseModel): ... and class Account(BaseModel): owner: User. When you create an Account instance from a dictionary, Pydantic expects the owner key to contain a dictionary that it can, in turn, parse and validate using the User model. This process is recursive and works for arbitrarily deep data structures.
WHEN TO USE IT: Use nested models whenever you are handling data that has a natural hierarchy. This is the standard pattern in web development with JSON APIs. For example, a BlogPost model that has an Author object and a list of Comment objects. It is also useful for complex configuration files where settings are grouped into logical sections.
WHEN NOT TO USE IT: Avoid nesting if the data relationship is truly flat; don't create a nested model for a single field if a simple type like str works, as it adds unnecessary complexity. Also, be mindful of circular dependencies (Model A needs Model B, and Model B needs Model A). While Pydantic can handle this, it can make code harder to reason about and may indicate your data model needs simplification.
ONE CANONICAL EXAMPLE: Imagine an API for a library. Instead of putting all author details directly in a book model, you create two models. First, an Author model: class Author(BaseModel): name: str; birth_year: int. Second, a Book model that uses it: class Book(BaseModel): title: str; author: Author. When parsing the JSON {'title': 'Pydantic Deep Dive', 'author': {'name': 'Alex', 'birth_year': 1990}}, Pydantic creates the Book object, sees the author field, and then uses the Author model to parse the inner dictionary, guaranteeing both the book and its author are valid.
Read the original → pydantic.dev
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.