I have the following setup:
class Response(BaseModel):
stuff1: int | None
stuff2: str
metadata: Metadata
class Metadata(BaseModel):
attr1: str
attr2: int | None = None
When Response is serialized/dumped as a JSON, I want attr2 to be included only if it is non-null. Importantly, stuff1 should be included regardless of its type (null or int). The exclude_none parameter to model.model_dump
would apply to all entries of response, so it is not suitable.
I know this feature is part of Pydantic 2.x but I am using 1.10.
desired dump result when response.metadata.attr2 = None
response = {
"stuff1": None
"stuff2": 4
"metadata": {
"attr1": "hello"
}
New contributor
duckasaur is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.