Assuming I have Pydantic-based FastAPI models similar to:
class Filter(BaseModel, extra=Extra.forbid):
expression: str | None
kind: str | None
...
class Configuration(BaseModel):
filter: Filter | None = {}
....
By default a model that is sent nothing for the filter will end up exporting like this:
{
"filter": {
"expression": None,
"kind": None,
...
},
...
}
What I want instead is this:
{
"filter": {},
...
}
What is the best way to have the nested model always have the exclude_unset behavior when exporting?
Sometimes in a complicated model I want some nested models to exclude unset fields but other ones to include them. I'm aware of exclude_unset and response_model_exclude_unset, but both affect the entire model.
It feels like there should be a way to specify behavior for a nested model and have the be consistently respected, but I can't find how to do this. Is there a better way to approach this?
source https://stackoverflow.com/questions/76105056/best-way-to-exclude-unset-fields-from-nested-fastapi-model-response
Comments
Post a Comment