Skip to content

Commit 0c0e391

Browse files
authored
Consider exclude_none in computed_field serialization (#768)
1 parent bf0bce0 commit 0c0e391

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

src/serializers/computed_fields.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,9 @@ impl ComputedField {
135135
let value = self
136136
.serializer
137137
.to_python(next_value, next_include, next_exclude, extra)?;
138+
if extra.exclude_none && value.is_none(py) {
139+
return Ok(());
140+
}
138141
let key = match extra.by_alias {
139142
true => self.alias_py.as_ref(py),
140143
false => property_name_py,

tests/serializers/test_model.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -605,6 +605,46 @@ def volume(self) -> int:
605605
assert s.to_json(Model(3, 4)) == b'{"width":3,"height":4,"Area":12,"volume":48}'
606606

607607

608+
def test_computed_field_to_python_exclude_none():
609+
@dataclasses.dataclass
610+
class Model:
611+
width: int
612+
height: int
613+
614+
@property
615+
def area(self) -> int:
616+
return self.width * self.height
617+
618+
@property
619+
def volume(self) -> None:
620+
return None
621+
622+
s = SchemaSerializer(
623+
core_schema.model_schema(
624+
Model,
625+
core_schema.model_fields_schema(
626+
{
627+
'width': core_schema.model_field(core_schema.int_schema()),
628+
'height': core_schema.model_field(core_schema.int_schema()),
629+
},
630+
computed_fields=[
631+
core_schema.computed_field('area', core_schema.int_schema(), alias='Area'),
632+
core_schema.computed_field('volume', core_schema.int_schema()),
633+
],
634+
),
635+
)
636+
)
637+
assert s.to_python(Model(3, 4), exclude_none=False) == {'width': 3, 'height': 4, 'Area': 12, 'volume': None}
638+
assert s.to_python(Model(3, 4), exclude_none=True) == {'width': 3, 'height': 4, 'Area': 12}
639+
assert s.to_python(Model(3, 4), mode='json', exclude_none=False) == {
640+
'width': 3,
641+
'height': 4,
642+
'Area': 12,
643+
'volume': None,
644+
}
645+
assert s.to_python(Model(3, 4), mode='json', exclude_none=True) == {'width': 3, 'height': 4, 'Area': 12}
646+
647+
608648
@pytest.mark.skipif(cached_property is None, reason='cached_property is not available')
609649
def test_cached_property_alias():
610650
@dataclasses.dataclass

0 commit comments

Comments
 (0)