Django Admin import_export module used for custom IMPORT

邮差的信 提交于 2019-12-08 02:34:44

问题


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.


回答1:


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')


来源:https://stackoverflow.com/questions/22655339/django-admin-import-export-module-used-for-custom-import

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!