diff --git a/CHANGELOG.md b/CHANGELOG.md index dd9e9461..6629294d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,9 @@ ## HEAD +### BUGFIX csv export with null foreign keys +CSV export will now work with null foreign keys + ### Chained qualifiers Chained qualifiers have been added [T35707](https://phabricator.codeyellow.nl/T35707). For more information on how they work and how to use it see [documentation](/docs/api.md) diff --git a/binder/plugins/views/csvexport.py b/binder/plugins/views/csvexport.py index aa6c18c1..72b0a6ab 100644 --- a/binder/plugins/views/csvexport.py +++ b/binder/plugins/views/csvexport.py @@ -289,6 +289,11 @@ def get_datum(data, key, prefix=''): else: # Assume that we have a mapping now fk_ids = data[head_key] + + # If foreign key is null don't try to fetch the data and stop + if not fk_ids: + return + if not isinstance(fk_ids, list): fk_ids = [fk_ids] diff --git a/tests/plugins/test_csvexport.py b/tests/plugins/test_csvexport.py index faf5a363..79888364 100644 --- a/tests/plugins/test_csvexport.py +++ b/tests/plugins/test_csvexport.py @@ -30,6 +30,7 @@ def setUp(self): animal = Animal(name='test') animal.save() + self.animal = animal self.pictures = [] for i in range(3): @@ -125,6 +126,19 @@ def test_download_extra_params(self): self.assertEqual(data[2], [str(caretaker_2.id), 'Bar', 'boo!']) self.assertEqual(data[3], [str(caretaker_3.id), 'Baz', 'boo!']) + def test_null_foreign_keys_will_not_fail(self): + response = self.client.get('/animal/download/') + self.assertEqual(200, response.status_code) + response_data = csv.reader(io.StringIO(response.content.decode("utf-8"))) + + data = list(response_data) + + # First line needs to be the header + self.assertEqual(data[0], ['ID', 'Zoo ID', 'Caretaker ID']) + + # All other data needs to be ordered using the default ordering (by id, asc) + self.assertEqual(data[1], [str(self.animal.id), '', '']) + def test_context_aware_download_xlsx(self): response = self.client.get('/picture/download/?response_type=xlsx') self.assertEqual(200, response.status_code) diff --git a/tests/testapp/views/animal.py b/tests/testapp/views/animal.py index 6f32a639..39861242 100644 --- a/tests/testapp/views/animal.py +++ b/tests/testapp/views/animal.py @@ -3,9 +3,12 @@ from binder.views import ModelView, Stat from ..models import Animal +from binder.plugins.views import CsvExportView # From the api docs -class AnimalView(ModelView): + + +class AnimalView(ModelView, CsvExportView): model = Animal m2m_fields = ['costume'] searches = ['name__icontains'] @@ -21,3 +24,11 @@ class AnimalView(ModelView): group_by='zoo.name', ), } + csv_settings = CsvExportView.CsvExportSettings( + withs=['zoo', 'caretaker'], + column_map=[ + ('id', 'ID'), + ('zoo.id', 'Zoo ID'), + ('caretaker.id', 'Caretaker ID'), + ], + )