quarta-feira, 22 de outubro de 2025

How to exclude fields from pydantic submodels model_dump()

 Everybody knows that using .model_dump() with exclude parameter we can exclude some attributes from the output. But if your model contains attributes that are other pytdantic models, and you want to hide some attributes of this submodel, the best solution, that are not so explicit in the pydantic documentation is define the attribute with annotated to be excluded, like this:

from pydantic import BaseModel, Field
from typing import Annotated

class MySubmodel(BaseModel):
      not_hidden_attr: str
      hidden_attr: Annotated[str, Field(exclude=True)]

class MyModel(BaseModel)
      attr_of_submodel: MySubmodel