django-import-export覆盖不起作用

时间:2017-10-10 16:42:47

标签: python django python-2.7 django-import-export

我正在重写django-import-export资源的方法。但只执行父方法。

models.py

class Model(models.Model):
     modelField1  = models.CharField(
     modelField2...
     modelField3...

admin.py

class ModelResource(resources.ModelResource):

    def before_import(self, dataset, using_transactions, dry_run, **kwargs):
        print("INside BEfore IMport")
        dataset.headers = ('modelField1', 'modelField2', ...)
        del dataset[0]

    def get_instance(self, instance_loader, row):
        print("Inside get instance")
        return False

    def get_or_init_instance(self, instance_loader, row):
        print("INside Get or init")
        instance = self.get_instance(instance_loader, row)
        if instance:
            return (instance, False)
        else:
            return (self.init_instance(row), True)

@admin.register(Model)
class ModelAdmin(ImportExportModelAdmin):
    class Meta:
        model = MOdel
        resource_class = ModelResource
        list_display = ('modelField1', 'modelField2', ...)
        search_fields = ('modelField1', 'modelField2', ...)

我根本没有在控制台中获取打印语句。直接从父方法抛出错误。它们根本不应该被执行。我说对了吗?

 Line number: 1 - u"Column 'id' not found in dataset. Available columns are: [u'Col1', u'Col2', u'Col2', ...]"
Traceback (most recent call last):
File "/home/aswin/projects/mastercityenv/local/lib/python2.7/site-packages/import_export/resources.py", line 434, in import_row
instance, new = self.get_or_init_instance(instance_loader, row)
File "/home/aswin/projects/mastercityenv/local/lib/python2.7/site-packages/import_export/resources.py", line 258, in get_or_init_instance
instance = self.get_instance(instance_loader, row)
File "/home/aswin/projects/mastercityenv/local/lib/python2.7/site-packages/import_export/resources.py", line 252, in get_instance
return instance_loader.get_instance(row)
File "/home/aswin/projects/mastercityenv/local/lib/python2.7/site-packages/import_export/instance_loaders.py", line 32, in get_instance
params[field.attribute] = field.clean(row)
File "/home/aswin/projects/mastercityenv/local/lib/python2.7/site-packages/import_export/fields.py", line 63, in clean
list(data.keys())))
KeyError: u"Column 'id' not found in dataset. Available columns are: [u'Col1', u'Col2', u'Col2', ...]"

其中Excel文档中的列名是“Col1”,“Col2”,......

问题:所以如果你注意到上面代码中的错误,那么它们来自我重载的父方法。他们为什么被执行?是不是应该执行代码在控制台中打印打印线?

1 个答案:

答案 0 :(得分:3)

根据documentation,不需要嵌套的Meta类。所以Admin类应该是:

@admin.register(Model)
class ModelAdmin(ImportExportModelAdmin):
    resource_class = ModelResource
    list_display = ('modelField1', 'modelField2', ...)
    search_fields = ('modelField1', 'modelField2', ...)