Performance: Nested models
This affects the server response time and client rendering speed by increasing data serialization and deserialization complexity.
from pydantic import BaseModel from fastapi import FastAPI app = FastAPI() class UserSummary(BaseModel): name: str class CompanySummary(BaseModel): name: str owner_name: str @app.get('/company') def get_company(): return CompanySummary(name='Acme', owner_name='Alice')
from pydantic import BaseModel from fastapi import FastAPI app = FastAPI() class Address(BaseModel): street: str city: str class User(BaseModel): name: str address: Address class Company(BaseModel): name: str owner: User @app.get('/company') def get_company(): return Company(name='Acme', owner=User(name='Alice', address=Address(street='123 Main', city='Town')))
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Deeply nested models | N/A (server-side) | N/A | Higher due to larger payload | [X] Bad |
| Flattened or simplified models | N/A (server-side) | N/A | Lower due to smaller payload | [OK] Good |
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