exclude_none
for specific fields only
#5461
Replies: 5 comments 10 replies
-
In v2 this could be done with a @samuelcolvin @adriangb is there any way we could make it possible for a Either way, I think it would be somewhat powerful if we could support this using a field serializer, as it would allow you to get the exclude-if-none behavior through a type annotation. |
Beta Was this translation helpful? Give feedback.
-
I have a very similar problem to this. I have a model of this form: class SuperModel(pydantic.BaseModel):
field: int | None = None
submodel: SubModel
class SubModel(pydantic.BaseModel):
field: int | None = None When serializing this, I want to always include the fields in m = SuperModel(submodel=SubModel())
print(m.model_dump_json(exclude_none=True))
# > {"submodel": {"field": null}} Basically, I want to ignore the @pydantic.model_serializer(mode="wrap")
def always_include_none(self, wrap: Callable[[Self], dict[str, Any]], info: pydantic.SerializationInfo) -> dict[str, Any]:
values = wrap(self)
for key, value in self.model_fields.items():
if info.exclude and key in info.exclude:
continue
if info.include and key not in info.include:
continue
if key not in values and getattr(self, key, None) is None:
values[value.alias if info.by_alias else key] = None
return values It would be nice if this was a builtin feature. Perhaps it can be an override in the config dict? class SubModel(pydantic.BaseModel):
config = pydantic.ConfigDict(exclude_none=False) Alternatively, maybe it can be a property of the field? class SuperModel(pydantic.BaseModel):
submodel: Annotated[SubModel, pydantic.Field(exclude_none=False)] |
Beta Was this translation helpful? Give feedback.
-
This feels like something that should be done with Edit: I thought about it a bit more and realized this doesn't actually lend itself to |
Beta Was this translation helpful? Give feedback.
-
I have the same problem with an API where 2-3 fields should not be part of the json if they are None, but the 15 other fields should be included |
Beta Was this translation helpful? Give feedback.
-
Inspired by previous responses, I came up with this solution, which works well enough for me at the moment—but I'd love to see a more ergonomic solution similar to what Adrian proposed. @dataclass
class OmitIfNone:
pass
class AppResponseModel(BaseModel):
@model_serializer
def _serialize(self):
omit_if_none_fields = {
k
for k, v in self.model_fields.items()
if any(isinstance(m, OmitIfNone) for m in v.metadata)
}
return {k: v for k, v in self if k not in omit_if_none_fields or v is not None}
class UserResponseModel(AppResponseModel):
id: int
deleted: Annotated[Literal[True] | None, OmitIfNone()] |
Beta Was this translation helpful? Give feedback.
-
Hi there! Apologies for asking stuff that is probably trivial, but couldn't find an answer to this.
I know it's possible to exclude
None
values globally. In my case, I'm generating a JSON response from FastAPI with Pydantic, and I would like to exclude only certain keys if None, but for all other fields, keep the default to showing null values, as sometimes they are meaningful.What would be the easiest way to achieve this? Thanks for your help 🙏
Beta Was this translation helpful? Give feedback.
All reactions