Nested Model
noun
say it: “NES-tid MOD-ul” /ˈnɛstɪd ˈmɑdəl/
In Pydantic, a model used as the type of another model's field, so an object inside the JSON body is checked by its own set of rules.
What is a nested model in Pydantic?
A nested model is a Pydantic model used as the type of another model's field, such as home: Home. The JSON
object inside the request body is checked by its own model, and an error's loc says where inside it the problem is.
from pydantic import BaseModel, ValidationError
class Home(BaseModel):
has_yard: bool
other_pets: int
class Application(BaseModel):
name: str
home: Home # a nested model: the inner object is checked by Home
application = Application.model_validate({"name": "Rosa", "home": {"has_yard": True, "other_pets": 1}})
print(application.home.has_yard) # True
try:
Application.model_validate({"name": "Rosa", "home": {"has_yard": True}})
except ValidationError as error:
print(error.errors()[0]["loc"]) # ('home', 'other_pets')
In a sentence
- “Rosa's application has a home object inside it, so the API checks it with a nested model called Home.”
- “Because Home is a nested model, a missing has_yard gets a 422 whose loc points at home, then has_yard.”
Level: Journeyman · More FastAPI terms at this level
Updated