Skip to content

Commit

Permalink
Consider exclude_none in computed_field serialization
Browse files Browse the repository at this point in the history
  • Loading branch information
hramezani committed Jul 13, 2023
1 parent bf0bce0 commit f7037b3
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/serializers/computed_fields.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,9 @@ impl ComputedField {
let value = self
.serializer
.to_python(next_value, next_include, next_exclude, extra)?;
if extra.exclude_none && value.is_none(py) {
return Ok(());
}
let key = match extra.by_alias {
true => self.alias_py.as_ref(py),
false => property_name_py,
Expand Down
40 changes: 40 additions & 0 deletions tests/serializers/test_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -605,6 +605,46 @@ 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():
@dataclasses.dataclass
class Model:
width: int
height: int

@property
def area(self) -> int:
return self.width * self.height

@property
def volume(self) -> None:
return None

s = SchemaSerializer(
core_schema.model_schema(
Model,
core_schema.model_fields_schema(
{
'width': core_schema.model_field(core_schema.int_schema()),
'height': core_schema.model_field(core_schema.int_schema()),
},
computed_fields=[
core_schema.computed_field('area', core_schema.int_schema(), alias='Area'),
core_schema.computed_field('volume', core_schema.int_schema()),
],
),
)
)
assert s.to_python(Model(3, 4), exclude_none=False) == {'width': 3, 'height': 4, 'Area': 12, 'volume': None}
assert s.to_python(Model(3, 4), exclude_none=True) == {'width': 3, 'height': 4, 'Area': 12}
assert s.to_python(Model(3, 4), mode='json', exclude_none=False) == {
'width': 3,
'height': 4,
'Area': 12,
'volume': None,
}
assert s.to_python(Model(3, 4), mode='json', exclude_none=True) == {'width': 3, 'height': 4, 'Area': 12}


@pytest.mark.skipif(cached_property is None, reason='cached_property is not available')
def test_cached_property_alias():
@dataclasses.dataclass
Expand Down

0 comments on commit f7037b3

Please sign in to comment.