Search code examples
djangodjango-import-export

importing an exported list JSONField turns JSON to string if JSON list is empty


I am using this answer from a similar question. But I would like to treat any empty fields from the import-export file as an empty list instead of None.

I have this resource:

some_list_json= fields.Field(attribute='some_list_json', 
    widget=JSONWidget(), 
    column_name='some_list_json')

With this field:

some_list_json = models.JSONField(default=list, blank=True, null=True)

When I try to export it, it doesn't show anything. And when I try to import and do some manipulation, it returns an exception.

'str' object has no attribute 'append'

How do I get around this?


Solution

  • You can override JSONWidget to handle this case:

    class EmptyListJSONWidget(JSONWidget):
        def clean(self, value, row=None, *args, **kwargs):
            val = super().clean(value)
            if not val:
                return list()
            return val
    
        def render(self, value, obj=None):
            if value is []:
                return value
            return json.dumps(value)
    

    Don't forget to update your resource field to reference this new widget instead of JSONWidget.

    Note that if you export this into csv, you will get [] in the field, you can adjust the code to return an empty string if preferred, then import / export will work as expected.