Skip to content
tezvyn:

Model an Order with a nested Product list in Pydantic

Source: pydantic.devMediumHow cards are made

Model an Order with a nested Product list in Pydantic

It tests Pydantic nested model composition. Define Product as BaseModel, then Order with products: list[Product]; Pydantic recursively coerces each dict and raises ValidationError on failure. A red flag is insisting on manual iteration.

What's really being asked

This question probes whether you understand declarative schema composition in Pydantic and how its validation engine handles nested data structures automatically. The interviewer wants to see that you know nested models are first-class citizens, not afterthoughts requiring manual parsing.

The full answer

First, define the child model Product by subclassing BaseModel and annotating name as a string and price as a float. Second, define the parent model Order with a field products annotated as a list of Product. Third, explain that passing a dictionary to Order.model_validate or the constructor triggers recursive validation where Pydantic instantiates each item in the list as a Product, coercing types and checking constraints. Fourth, note that if any element fails, Pydantic raises a ValidationError that includes the exact path such as products followed by the index of the offending item. Fifth, mention that this works because Pydantic treats annotated fields as part of the schema graph and resolves them during core schema generation, so no extra wiring is needed for standard nesting.

The mistakes people make

A red flag is proposing a manual for-loop inside an init method or a custom validator to construct Product objects one by one, which ignores Pydantic's built-in recursive machinery. Another red flag is using untyped lists like list without parameterizing them with Product, which disables nested validation and treats items as opaque objects. A third red flag is confusing Pydantic validation with simple JSON deserialization, implying that the library only checks top-level keys and ignores inner structure or type safety.

What usually comes next

The interviewer may ask how you would handle a variable number of nested items or optional fields inside Product. They might ask about performance implications of deep nesting or how to customize error messages for specific items. Another follow-up is how to use RootModel if the top-level payload is just a list of orders rather than a single object, or how to enforce unique product names within the list.

A concrete example

Imagine an order payload with two products where the second product has a negative price. When Order.model_validate is called, Pydantic successfully creates the first Product, then detects the invalid float constraint on the second item. The resulting ValidationError contains a loc tuple pointing to products, index one, and price, making it trivial for an API consumer to pinpoint the issue without writing custom error logic or recursive inspection code.

Interview question

An Order model needs to hold a list of Product models. What is the idiomatic Pydantic way to ensure nested dictionaries are validated and coerced automatically?

  • a.Parse the payload with a JSON library first, then pass the resulting objects to Order to avoid nested validation overhead.
  • b.Annotate the field as list[Product] where Product subclasses BaseModel, relying on Pydantic's recursive schema resolution.Correct
  • c.Define products as list and attach a field_validator that manually constructs Product instances from each dictionary.
  • d.Override __init__ in Order to iterate over the raw list and build Product objects before assignment.
Why?

Annotating the field as list[Product] leverages Pydantic's core schema generation to recursively validate nested items and report precise error paths automatically. Overriding __init__ to manually build Product instances is a red flag because it ignores Pydantic's built-in recursive validation machinery.

Just read this? Test yourself on what you have been reading.

Read the original → pydantic.dev

You just looked this up. Could you explain it out loud?

That is the part interviews actually test. Tezvyn takes questions like this one and gives you what the interviewer is really checking, the answer that lands, and the mistake that ends the conversation, in the four minutes before your next meeting.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on pydantic — each one lists the topics its interview covers.

See open roles