Introduction
Nested models help organize related data inside other data, making it easier to manage and understand complex information.
from pydantic import BaseModel class InnerModel(BaseModel): field1: str field2: int class OuterModel(BaseModel): inner: InnerModel other_field: float
from pydantic import BaseModel class Address(BaseModel): street: str city: str class User(BaseModel): name: str address: Address
from pydantic import BaseModel from typing import List class Item(BaseModel): name: str price: float class Order(BaseModel): items: List[Item] total: float
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Address(BaseModel): street: str city: str class User(BaseModel): name: str age: int address: Address @app.post("/users/") async def create_user(user: User): return {"message": f"User {user.name} from {user.address.city} created."}
nested models in FastAPI?class Item(BaseModel): name: str; price: float class Order(BaseModel): id: int; item: Item
Order(id=1, item={'name': 'Book', 'price': 12.5}).item.price?item.price returns the float value 12.5 from the nested Item model.class Profile(BaseModel): age: int
class User(BaseModel): username: str; profile = {"age": 30}profile: Profile = {"age": 30} or profile: Profile = Profile(age=30) to enable nested model validation.name and email. The post has title, content, and author. Which code correctly defines these nested models and validates that the author's email is a valid email address?Pass the test and this pattern moves unknown