django - 将 .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 文件保存到数据库时发生此错误(列表索引超出范围)。
解决方案
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 文件。
希望这可以帮助..!
推荐阅读
- pandas - Pandas 条形图比较两个不同年份的天数
- jenkins - 如何将变量从 Jenkins 种子作业传递给作业
- r - R中ifelse语句中的多个和或条件,得到意外的输出
- c++ - 为什么这个链表程序没有给出任何输出?
- java - 如何使用 Java 清除 Excel 过滤器
- python - AttributeError:部分初始化的模块“speech_recognition”没有属性“Recognizer”(很可能是由于循环导入)
- android - 使用 ViewBinding 测试片段场景
- android - 构建签名的 apk 时出错。错误是“密钥库被篡改,或密码不正确”
- c# - 如果反序列化失败,则跳过 Cosmos DB 容器中的文档
- javascript - 新事件()与 document.createEvent()