Skip to content

Commit 42394ac

Browse files
Fix model computed field serializer (json) (#1187)
1 parent dcaf63e commit 42394ac

File tree

2 files changed

+46
-1
lines changed

2 files changed

+46
-1
lines changed

src/serializers/computed_fields.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ impl ComputedFields {
7575
let property_name_py = computed_field.property_name_py.as_ref(model.py());
7676
let value = model.getattr(property_name_py).map_err(py_err_se_err)?;
7777
if extra.exclude_none && value.is_none() {
78-
return Ok(());
78+
continue;
7979
}
8080
if let Some((next_include, next_exclude)) = filter
8181
.key_filter(property_name_py, include, exclude)

tests/serializers/test_model.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -650,6 +650,51 @@ def volume(self) -> None:
650650
assert s.to_json(Model(3, 4), exclude_none=True) == b'{"width":3,"height":4,"Area":12}'
651651

652652

653+
def test_computed_field_exclude_none_different_order():
654+
# verify that order of computed fields doesn't matter
655+
# issue originally reported via: https://github.com/pydantic/pydantic/issues/8691
656+
657+
@dataclasses.dataclass
658+
class Model:
659+
width: int
660+
height: int
661+
662+
@property
663+
def volume(self) -> None:
664+
return None
665+
666+
@property
667+
def area(self) -> int:
668+
return self.width * self.height
669+
670+
s = SchemaSerializer(
671+
core_schema.model_schema(
672+
Model,
673+
core_schema.model_fields_schema(
674+
{
675+
'width': core_schema.model_field(core_schema.int_schema()),
676+
'height': core_schema.model_field(core_schema.int_schema()),
677+
},
678+
computed_fields=[
679+
core_schema.computed_field('volume', core_schema.int_schema()),
680+
core_schema.computed_field('area', core_schema.int_schema(), alias='Area'),
681+
],
682+
),
683+
)
684+
)
685+
assert s.to_python(Model(3, 4), exclude_none=False) == {'width': 3, 'height': 4, 'Area': 12, 'volume': None}
686+
assert s.to_python(Model(3, 4), exclude_none=True) == {'width': 3, 'height': 4, 'Area': 12}
687+
assert s.to_python(Model(3, 4), mode='json', exclude_none=False) == {
688+
'width': 3,
689+
'height': 4,
690+
'Area': 12,
691+
'volume': None,
692+
}
693+
assert s.to_python(Model(3, 4), mode='json', exclude_none=True) == {'width': 3, 'height': 4, 'Area': 12}
694+
assert s.to_json(Model(3, 4), exclude_none=False) == b'{"width":3,"height":4,"volume":null,"Area":12}'
695+
assert s.to_json(Model(3, 4), exclude_none=True) == b'{"width":3,"height":4,"Area":12}'
696+
697+
653698
@pytest.mark.skipif(cached_property is None, reason='cached_property is not available')
654699
def test_cached_property_alias():
655700
@dataclasses.dataclass

0 commit comments

Comments
 (0)