Django-import-export 继承resources.ModelResource 重写方法不生效问题
我们随便在网上找一篇文章,关于django-import-export
插件的,都是以下的写法:
python
class ReturnGoodsResource(resources.ModelResource):
#任意重写个方法,都不会生效
def before_import_row(self, row, **kwargs):
print(row)
class Meta:
model = ReturnGoods
@admin.register(ReturnGoods)
class ReturnGoodsAdmin(ImportExportModelAdmin):
resources = ReturnGoodsResource
class ReturnGoodsResource(resources.ModelResource):
#任意重写个方法,都不会生效
def before_import_row(self, row, **kwargs):
print(row)
class Meta:
model = ReturnGoods
@admin.register(ReturnGoods)
class ReturnGoodsAdmin(ImportExportModelAdmin):
resources = ReturnGoodsResource
各种调试,查阅文档,都没解决。后来查看官方的demo,发现就一个地方写法有问题。这个问题可能是由于版本升级造成的。
最新版本的 admin中指定resource要用resource_class
而不是resources
,就这一个小小的却别。
改成下方这种写法就可以了:
python
class ReturnGoodsResource(resources.ModelResource):
def before_import_row(self, row, **kwargs):
print(row)
class Meta:
model = ReturnGoods
@admin.register(ReturnGoods)
class ReturnGoodsAdmin(ImportExportModelAdmin):
resource_class = ReturnGoodsResource
class ReturnGoodsResource(resources.ModelResource):
def before_import_row(self, row, **kwargs):
print(row)
class Meta:
model = ReturnGoods
@admin.register(ReturnGoods)
class ReturnGoodsAdmin(ImportExportModelAdmin):
resource_class = ReturnGoodsResource
具体写法可以参考这个官方给出的demo(码云镜像地址):
https://gitee.com/tompeppa/django-import-export/blob/master/tests/core/admin.py
作者:贝塔博客