Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixing exclude_none for json serialization of computed_fields #1098

Merged
merged 1 commit into from Nov 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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(());
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As per pydantic/pydantic#8691, should this be a continue instead of 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