From 9cec57e09267747b1d2ec66c3d1e23ab5f3b57d5 Mon Sep 17 00:00:00 2001 From: Rob van Diepen Date: Wed, 4 Oct 2023 12:24:43 +0200 Subject: [PATCH 1/2] Support nullable ListFields with django-rest-framework --- drf_excel/fields.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/drf_excel/fields.py b/drf_excel/fields.py index 2cbd16c..4caca58 100644 --- a/drf_excel/fields.py +++ b/drf_excel/fields.py @@ -159,7 +159,9 @@ def __init__(self, list_sep, **kwargs): super().__init__(**kwargs) def prep_value(self) -> Any: - if len(self.value) > 0 and isinstance(self.value[0], Iterable): + if self.value is None: + return super().prep_value() + elif len(self.value) > 0 and isinstance(self.value[0], Iterable): # array of array; write as json return json.dumps(self.value, ensure_ascii=False) else: From 65e8874e12b64d653376d27f32599c3f9842d653 Mon Sep 17 00:00:00 2001 From: Bruno Alla Date: Fri, 11 Oct 2024 20:59:24 +0100 Subject: [PATCH 2/2] Expand test suite to cover null and empty list values in XLSXListField --- tests/test_fields.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/tests/test_fields.py b/tests/test_fields.py index 0789d00..112e09c 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -444,6 +444,36 @@ def test_cell_complex_types(self, style: XLSXStyle, worksheet: Worksheet): assert isinstance(cell, Cell) assert cell.value == '[{"a": 1}, {"b": 2}]' + def test_cell_with_empty_list(self, style: XLSXStyle, worksheet: Worksheet): + f = XLSXListField( + list_sep=None, + key="objs", + value=[], + field=ListField(), + style=style, + mapping="", + cell_style=style, + ) + assert f.original_value == f.value == [] + cell = f.cell(worksheet, 1, 1) + assert isinstance(cell, Cell) + assert cell.value == "" + + def test_cell_with_null_value(self, style: XLSXStyle, worksheet: Worksheet): + f = XLSXListField( + list_sep=None, + key="objs", + value=None, + field=ListField(allow_null=True), + style=style, + mapping="", + cell_style=style, + ) + assert f.original_value is f.value is None + cell = f.cell(worksheet, 1, 1) + assert isinstance(cell, Cell) + assert cell.value is None + class TestXLSXBooleanField: @pytest.mark.parametrize("value", [True, False])