From f94b5e3debdeebed9c794178384d13732a9894f8 Mon Sep 17 00:00:00 2001 From: sydney-runkle Date: Wed, 29 Nov 2023 11:03:21 -0600 Subject: [PATCH] fixing exclude_none for json serialization of computed fields --- src/serializers/computed_fields.rs | 4 ++++ tests/serializers/test_model.py | 4 +++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/src/serializers/computed_fields.rs b/src/serializers/computed_fields.rs index 8a1f041ae..6f4553069 100644 --- a/src/serializers/computed_fields.rs +++ b/src/serializers/computed_fields.rs @@ -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)? diff --git a/tests/serializers/test_model.py b/tests/serializers/test_model.py index 32ecd3c1a..4249c3015 100644 --- a/tests/serializers/test_model.py +++ b/tests/serializers/test_model.py @@ -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 @@ -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')