简体   繁体   中英

Django Admin import_export module used for custom IMPORT

I was trying to follow official doc of import-export :

https://django-import-export.readthedocs.org/en/latest/import_workflow.html#import-data-method-workflow

But I still do not know how to glue it to my admin assuming that :

  1. I want only subset of fields (I created Resource model with listed fields, but It crashes while importing anyway with: KeyError full stack bellow.

  2. Where - in which method - in my admin class (inheriting of course ImportExportModelAdmin and using defined resource_class ) should i place the code responsible for some custom actions I want to happen after validating, that import data are correct but before inserting them into database.

I am not very advanced in Django and will be thankful for some hints. Example of working implementation will be appreciated, so if you know something similar on github - share.

you can override it as

to create a new instance

def get_instance(self, instance_loader, row):
    return False

your custom save

def save_instance(self, instance, real_dry_run):
    if not real_dry_run:
            try:
                obj = YourModel.objects.get(some_val=instance.some_val)
                # extra logic if object already exist
            except NFCTag.DoesNotExist:
                # create new object
                obj = YourModel(some_val=instance.some_val)
                obj.save()

def before_import(self, dataset, dry_run):

    if dataset.headers:
        dataset.headers = [str(header).lower().strip() for header in dataset.headers]

      # if id column not in headers in your file
    if 'id' not in dataset.headers:
        dataset.headers.append('id')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM