Django提供了一个
我想知道是否可以导入数据,但使用的表没有名为id的列
我的导入对每个包含列id的表都很好,但对不包含列id的表则不起作用。我收到一个row_error,上面写着:Error: 'id'
无法导入的型号
class CustomizingObject(models.Model):
code = models.CharField(max_length=40, primary_key=True, unique=True, help_text="Human readable code")
我的功能
from import_export import resources
lo_resource = resources.modelresource_factory(model=lo_resource_to_import)() # lo_resource_to_import is the model
with open(lv_local_filename, 'r', encoding='utf-8') as f:
csv_data = f.read()
lt_dataset = tablib.Dataset().load(csv_data, 'csv')
result = lo_resource.import_data(lt_dataset, dry_run=True)
if not result.has_errors():
result = lo_resource.import_data(lt_dataset, dry_run=False)
Logger.Info("import", 2) # Import over
else :
Logger.Error("import", 3, lv_local_filename) # Input file {} has error
for ld_error in result.row_errors():
Logger.Error("import", 5, ld_error[1][0].error) # Error: {}
import_id_fields
,这样我们就可以指定要导入的字段。如果没有它,它总是寻找字段ID
。
解决方案是用resources.ModelResource
对我的类进行封装,并指定import_id_fields
。
class CustomizingObjectResource(resources.ModelResource):
class Meta:
model = CustomizingObject
import_id_fields = ('code',)
fields = ('code')
我的功能
# specific is a parameter of my function here specific = CustomizingObjectResource
if specific is not None:
lo_resource = specific()
else:
lo_resource = resources.modelresource_factory(model=lo_resource_to_import)()
with open(lv_local_filename, 'r', encoding='utf-8') as f:
csv_data = f.read()
lt_dataset = tablib.Dataset().load(csv_data, 'csv')
result = lo_resource.import_data(lt_dataset, dry_run=True)
if not result.has_errors():
result = lo_resource.import_data(lt_dataset, dry_run=False)
Logger.Info("import", 2) # Import over
else :
Logger.Error("import", 3, lv_local_filename) # Input file {} has error
for ld_error in result.row_errors():
Logger.Error("import", 5, ld_error[1][0].error) # Error: {}