Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 38 ยท Models and Types

Nested Models and Collections

Validate lists, dicts, sets and tuples in Pydantic, nest models inside models, handle self-referencing trees with forward references, and read error locations.

Real data is nested: an order contains items, an item has a product, a category has subcategories. Pydantic validates the whole structure in one call, descending into every list and dictionary. This lesson shows how collections and nested models work, and how errors point to the exact spot deep inside the data.

Collections of simple values

Use the built-in generic types: list[int], dict[str, float], set[str], tuple[int, int]. Pydantic checks every element and converts it where it can.

Python Typed collections

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Things to notice:

  • The list ["10", 20, 30.0] becomes [10, 20, 30].
  • A set removes duplicates; sets and tuples become JSON arrays.
  • tuple[float, float] has a fixed length of two; tuple[int, ...] allows any length.
  • Dictionary keys are validated too, not only values.

Nested models

A field can be annotated with another model. Input for it is a nested dict (or a ready-made model instance).

Python Models inside models

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

One call to model_validate converted a whole tree of dictionaries into typed objects, and model_dump turns the tree back into dictionaries.

flowchart TD
    O["Order<br/>id: int"] --> L1["OrderLine<br/>quantity: int"]
    O --> L2["OrderLine<br/>quantity: int"]
    L1 --> P1["Product<br/>sku, price"]
    L2 --> P2["Product<br/>sku, price"]

Validation recurses through every level of the structure.

Errors tell you where

When something deep inside is wrong, the error's loc is a path of keys and list indexes:

Python Error locations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The location ('lines', 1, 'product', 'price') means "the price of the product of line number 1" (counting from 0). API clients can use it to highlight the exact input box.

Self-referencing models

Trees, comments with replies and organisation charts contain their own type. Use a string annotation (a forward reference) for the class inside itself:

Python A tree of categories

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

If two models refer to each other and are defined in any order, a forward reference may need Model.model_rebuild() after both classes exist. Pydantic usually does this automatically and tells you when it cannot.

Mapping and sequence abstract types

Annotations can also use Sequence[int], Mapping[str, int] and Iterable[int] from collections.abc. They accept any matching input but are less strict about the concrete type, so prefer list and dict unless you need the flexibility.

Mutable defaults are safe

Unlike a plain Python function, children: list["Category"] = [] is safe in a Pydantic model: the default is copied for each instance. If you prefer to be explicit, Field(default_factory=list) does the same.

For large lists of simple values, validation cost grows with the number of items. For very large payloads see Performance later in the tutorial.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does tuple[int, ...] mean?

    The ellipsis means 'any number of'. tuple[int, int] would be exactly two.
  2. 2. In an error with loc ('lines', 1, 'product', 'price'), what does the 1 refer to?

    List positions appear as integers in the location path, counted from zero.
  3. 3. How do you annotate a model field that holds children of the same class?

    Inside the class body the name does not exist yet, so use a string (forward reference).
  4. 4. What happens to duplicates when you validate ['a', 'b', 'a'] into a set[str] field?

    A set cannot contain duplicates, so the result has two items.

Summary

  • Use list[T], dict[K, V], set[T], tuple[A, B] and tuple[T, ...]; every element (and every dict key) is validated and converted.
  • A field annotated with a model validates nested dicts, to any depth, in one call.
  • Error loc paths show the keys and list indexes down to the failing value.
  • Self-referencing models use a string annotation such as list["Category"].
  • Mutable defaults like [] are copied per instance in Pydantic models.

Next: Unions and Literals