首页 > 解决方案 > 将 .csv 保存到数据库时发生错误:-'列表索引超出范围'

问题描述

def import_db(request):
    f=open('product.csv','r')
    for row in f:
      row =  row.split('!')
      tmp = AdminProduct.objects.create()

      tmp.id = row[0]
      tmp.productname = row[1]
      tmp.barcode = row[2]
      tmp.company = row[3]
      tmp.size = row[4]
      tmp.price = row[5]
      tmp.description = row[6]
      tmp.category = row[7]
      tmp.subcategory = row[8]
      tmp.product_tag = row[9]
      tmp.image = row[10]
      tmp.save()

    f.close()   

将 .csv 文件保存到数据库时发生此错误(列表索引超出范围)。

标签: djangopython-3.xdjango-modelsdjango-rest-framework

解决方案


import csv #will get csv from python

def import_db(request):
    with open('product.csv','r') as csv_file:
    csv_reader = csv.reader(csv_file)
    row1=True   #will skip your first row and mismatching of variable type
    for row in csv_reader:
        if row1:
            row1 = False
            continue

        tmp = AdminProduct.objects.create(
             id          = row[0],
             productname = row[1],
             barcode     = row[2],
             company     = row[3],
             size        = row[4],
             price       = row[5],
             description = row[6],
             category    = row[7],
             subcategory = row[8],
             product_tag = row[9],
             image       = row[10],
             )
    return redirect('/somewhere/')   

当您上传 .csv 时,其背后的逻辑与网络上的逻辑相同,您需要检查的是您要插入的 .csv 数据的数据类型以及数据库表具有的匹配列。它们都必须是相同的。
此外,最好使用某种库来导入-导出 .csv 文件。
希望这可以帮助..!


推荐阅读