I have the following structures:
models.py:
class PublicPerson(models.Model):
class Meta:
verbose_name = "Public Person"
verbose_name_plural = "Public People"
user = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="public_profile", null=True)
name = models.CharField(max_length=100)
image = models.ImageField(upload_to='public_persons/images', null=True)
date_of_birth = models.DateField(null=True, blank=True)
bio = models.TextField(max_length=10000, blank=True, null=True)
short_description = models.CharField(max_length=200, blank=True, null=True)
meta_fields = models.JSONField(default=dict, blank=True, null=True)
admin.py
from import_export.admin import ImportExportModelAdmin
from import_export import resources, widgets, fields as f
class PublicPersonResource(resources.ModelResource):
meta_fields = f.Field(attribute='meta_fields', column_name='meta_fields')
def dehydrate_meta_fields(self, public_person):
meta_fields = getattr(public_person, 'meta_fields', None)
if meta_fields:
return meta_fields
return {}
class PublicPersonAdmin(ImportExportModelAdmin):
...
resource_class = PublicPersonResource
...
I am usning django-import-export, and trying to get a more user-friendly import/export capability for the JsonField. More specifically, I have some nested Json data, which I would like to be able to import from / export to an excel (and/or csv if possible) file with a very specific format.
So far, I have been able to modify only the export to Json by defining the 'dehydrate_meta_fields' method. I am not sure how to approach the other cases. Thus, export to and import from json seems to work just fine with nested data
The level of nesting is not expected to change. It will always be a string : string dictionary, however new fields may be added in the future. This new fields will be added rare enough that hardcoding them is acceptable if this is the only option
example json data:
[
{
"meta_fields": {
"filed1": "some",
"filed2": "data",
"filed3": "is",
"filed4": "here"
},
"id": 11,
"user": 1,
"name": "test",
"image": "public_persons/images/Capture.PNG",
"date_of_birth": "2023-10-23",
"party": 1,
"bio": "",
"short_description": ""
}
]
desired output: (Note the formatting for the 'meta_fields')
xlsx:
Edit 1: I noticed that django-import-export uses Tablib to handle the import and exporting. Reading though the docs I noticed that Pandas can be used by as a data-source for Tablib. Thus, I have managed to import my xlsx/csv data into a pandas MultiIndex dataframe, and then into a Tablib dataset just fine. Two issues now remain however:
- Django-import-export throws an error due to an unexpected column structure. how would I overwrite that?
- How do I overwrite the creation of the Tablib dataset in my PublicPersonResource?