Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python Pydantic Nested Models, Lists, and Enums

Learn how to define and validate nested models, lists of models, and enum fields in Pydantic with clear examples, including optional values and common pitfalls.

~4 min readPython
#pydantic#data validation#nested models#enums
Diagram showing a Pydantic model with nested model, list of models, and enum fields

Pydantic makes it straightforward to model nested objects, lists of objects, and fields that accept a fixed set of choices. These patterns are common in API request and response schemas, configuration files, and data pipelines. The examples below show how to define the structures and how Pydantic validates them at runtime.

Defining a Nested Model

A nested model is a Pydantic model used as the type of a field in another model. Pydantic treats it like any other field type and instantiates and validates the inner model when the outer model is created.

python
from pydantic import BaseModel class Address(BaseModel): street: str city: str zip_code: str class User(BaseModel): name: str address: Address

When you create a User, the address field can be an Address instance or a dictionary. If you pass a dictionary, Pydantic converts it to an Address and validates its fields. If validation fails, the error is reported on the address field, and Pydantic preserves the nested error details.

Using Lists of Models

A list of models is declared with list[Model]. Pydantic validates each element in the list against the model.

python
from pydantic import BaseModel class LineItem(BaseModel): sku: str quantity: int class Order(BaseModel): items: list[LineItem]

When you create an Order, each item in the items list must be a dictionary or a LineItem instance. Pydantic validates every element and includes the index of any invalid item in the validation error. If one element is invalid, the whole Order creation fails.

Enums as Field Types

Enums restrict a field to a fixed set of allowed values. Pydantic accepts the enum member itself or, for str-based enums, the corresponding string value.

python
from enum import Enum from pydantic import BaseModel class Status(str, Enum): pending = "pending" shipped = "shipped" delivered = "delivered" class Shipment(BaseModel): id: str status: Status

Using str as the base class keeps the enum members JSON-serializable as strings. When you create a Shipment, you can pass status="shipped" or status=Status.shipped; Pydantic coerces the string to the enum member. An invalid value raises a validation error.

How Validation Propagates Through Nested Structures

Pydantic validates the whole object graph recursively when you create a model instance. A nested model is validated when the outer model is constructed, and lists are validated element by element. The same rules apply to deeper nesting: a model inside a list inside another model is still fully validated.

This is useful because it catches invalid data at the boundary of your application rather than deep inside business logic. The tradeoff is that one invalid field in a large nested structure causes the entire object creation to fail. If you need to accept partially missing data, define dedicated models with optional fields for the parts that may be absent; Pydantic does not provide built-in partial validation for a single model call.

Handling Optional and Default Values

Lists, nested models, and enums can all be optional or have defaults. Use Optional[...] from typing (or a | None union on Python 3.10+) and a default value to allow a field to be omitted.

python
from typing import Optional from pydantic import BaseModel, Field class Product(BaseModel): name: str tags: list[str] = Field(default_factory=list) category: Optional[str] = None

For mutable defaults such as lists or dictionaries, use Field(default_factory=...) so each instance gets a fresh object and instances do not share state.

For enums, set a default enum member:

python
class Order(BaseModel): status: Status = Status.pending

A field with a None default is set to None when omitted; a field with another default uses that value. This is especially useful for API models where some fields are only present in certain responses.

Common Pitfalls with Nested Models and Enums

Avoid using a mutable default like [] for a list field. Use default_factory=list so each model instance gets a fresh list and no state is shared between instances. Another common issue is confusing the enum member with its value: model.status is the enum member, not the raw string. If you need the value, use model.status.value.

When nesting models, remember that Pydantic accepts a dictionary or an instance of the model for a nested field; it does not parse a JSON string into a nested model automatically. If you want to initialize from ORM objects, configure from_attributes=True on the model.

When to Split Models vs. Use Dict

For one-off structures, using dict as a field type may be tempting because it needs less code. However, you lose validation, type hints, and IDE support. Nested models give explicit structure and automatic validation at the cost of extra class definitions. Use a separate model when the nested shape is reused or needs validation; reserve dict for genuinely flexible data that you will validate manually. In API schemas and configuration files, nested Pydantic models are usually worth the extra declaration because they expose the schema and catch errors early.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.