Skip to content

Commit

Permalink
Fixing exclude_none for json serialization of computed_fields (#1098
Browse files Browse the repository at this point in the history
)
  • Loading branch information
sydney-runkle committed Nov 29, 2023
1 parent c7daf16 commit 3b6344e
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 1 deletion.
4 changes: 4 additions & 0 deletions src/serializers/computed_fields.rs
Expand Up @@ -73,6 +73,10 @@ impl ComputedFields {
}
for computed_field in &self.0 {
let property_name_py = computed_field.property_name_py.as_ref(model.py());
let value = model.getattr(property_name_py).map_err(py_err_se_err)?;
if extra.exclude_none && value.is_none() {
return Ok(());
}
if let Some((next_include, next_exclude)) = filter
.key_filter(property_name_py, include, exclude)
.map_err(py_err_se_err)?
Expand Down
4 changes: 3 additions & 1 deletion tests/serializers/test_model.py
Expand Up @@ -608,7 +608,7 @@ def volume(self) -> int:
assert s.to_json(Model(3, 4)) == b'{"width":3,"height":4,"Area":12,"volume":48}'


def test_computed_field_to_python_exclude_none():
def test_computed_field_exclude_none():
@dataclasses.dataclass
class Model:
width: int
Expand Down Expand Up @@ -646,6 +646,8 @@ def volume(self) -> None:
'volume': None,
}
assert s.to_python(Model(3, 4), mode='json', exclude_none=True) == {'width': 3, 'height': 4, 'Area': 12}
assert s.to_json(Model(3, 4), exclude_none=False) == b'{"width":3,"height":4,"Area":12,"volume":null}'
assert s.to_json(Model(3, 4), exclude_none=True) == b'{"width":3,"height":4,"Area":12}'


@pytest.mark.skipif(cached_property is None, reason='cached_property is not available')
Expand Down

0 comments on commit 3b6344e

Please sign in to comment.