Last active
December 21, 2022 03:11
-
-
Save lightstrike/ddf58986e182381851373ae315189df1 to your computer and use it in GitHub Desktop.
Before Import Customization for Django-Import-Export
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class OrganizationImportExportResource(ModelResource): | |
types = widgets.ManyToManyWidget(model=graph_models.OrganizationType, | |
field='name') | |
class Meta: | |
model = Organization | |
fields = [ | |
'name', | |
] | |
import_id_fields = ['name'] | |
export_order = fields | |
skip_unchanged = True | |
def before_import(self, dataset, dry_run, **kwargs): | |
""" | |
Pre-processes import data in following four ways: | |
1. Strip empty space around organization name | |
2. Concantenate organization types for ManyToManyWidget | |
3. Create columns that map to database fields | |
4. Drop original columns | |
""" | |
template_headers = [h for h in dataset.headers] | |
# strip spaces from organization name | |
cleaned_names = [d.strip() for d in dataset[template_headers[0]]] | |
dataset.append_col(cleaned_names, header='name') | |
types_values = [','.join([d[1].strip(), | |
d[2].strip(), | |
d[3].strip()]) for d in dataset] | |
dataset.append_col(types_values, header='types') | |
for column in template_headers: | |
del dataset[column] | |
super(OrganizationImportExportResource, self).before_import(dataset, | |
dry_run, **kwargs) | |
def skip_row(self, instance, original): | |
""" | |
Skip rows with empty organization names, | |
necessary since Organization model allows blank names. | |
""" | |
if instance.name: | |
super(OrganizationImportExportResource, self).skip_row(instance, original) | |
else: | |
return True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment