Skip to content

Commit

Permalink
Adjust model serializer.
Browse files Browse the repository at this point in the history
Fixes #147.
  • Loading branch information
eseglem committed Sep 28, 2023
1 parent 6bf9487 commit 493fe05
Showing 1 changed file with 9 additions and 5 deletions.
14 changes: 9 additions & 5 deletions geojson_pydantic/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,8 @@ def validate_bbox(cls, bbox: Optional[BBox]) -> Optional[BBox]:

return bbox

@model_serializer(when_used="json", mode="wrap")
def clean_model(self, serializer: Any, _info: SerializationInfo) -> Dict[str, Any]:
@model_serializer(when_used="always", mode="wrap")
def clean_model(self, serializer: Any, info: SerializationInfo) -> Dict[str, Any]:
"""Custom Model serializer to match the GeoJSON specification.
Used to remove fields which are optional but cannot be null values.
Expand All @@ -62,7 +62,11 @@ def clean_model(self, serializer: Any, _info: SerializationInfo) -> Dict[str, An
# We want to avoid forcing values in `exclude_none` or `exclude_unset` which could
# cause issues or unexpected behavior for downstream users.
data: Dict[str, Any] = serializer(self)
for field in self.__geojson_exclude_if_none__:
if field in data and data[field] is None:
del data[field]

# Only remove fields when in JSON mode.
if info.mode_is_json():
for field in self.__geojson_exclude_if_none__:
if field in data and data[field] is None:
del data[field]

return data

0 comments on commit 493fe05

Please sign in to comment.