Django - 导入导出 - 从Excel保存字段名称



我有一个看起来像这样的模型:

class ExcelData(models.Model):
var1                        = models.IntegerField() 
var2                        = models.IntegerField() 
var3                        = models.IntegerField() 

和一个包含 3 列(col1、col2、col3(的 Excel 工作表。

我想在导入 excel 文件时用列名称覆盖模型的字段名称。

预期成果:

class ExcelData(models.Model):
col1                        = models.IntegerField() 
col2                        = models.IntegerField() 
col3                        = models.IntegerField() 

实际结果:

"Column 'id' not found in dataset. Available columns are ... "

这就是我走多远:

@admin.register(ExcelData)
class ViewAdmin(ImportExportModelAdmin):
exclude = ('id',)
class ExcelDataResource(resources.ModelResource):
var1 = Field(attribute='var1', column_name='Custom 1')
var2 = Field(attribute='var2', column_name='Custom 2')
var3 = Field(attribute='var3', column_name='Custom 3')
class Meta:
model = ExcelData
fields = ()
import_id_fields = ('var1',)
export_order = ()

感谢您的任何建议

你可以在列名 doc:https://django-import-export.readthedocs.io/en/latest/getting_started.html#exporting-data 中指定它

class ExcelResource(resources.ModelResource):
var1 = Field(attribute='var1', column_name='Custom Name')
var2 = Field(attribute='var2', column_name='Custom Name')
var3 = Field(attribute='var3', column_name='Custom Name')

class Meta:
model = ExcelData
fields = ( var1, var2, var3 )
export_order = ( var1, var2, var3 )

ExcelData 需要更新才能具有主键:

class ExcelData(models.Model):
col1 = models.IntegerField(primary_key=True) 
col2 = models.IntegerField() 
col3 = models.IntegerField() 

相关内容

  • 没有找到相关文章

最新更新