我正在尝试将csv上传到Django表中。我无法将数据与外键匹配。 “ cpt”是从价格到服务模式的外键。有许多价格行映射到一个cpt行,但是每一行只有一个cpt。
这是我的上传代码。
path = "/Users/joannerodrigues/Documents/csv_import/"
os.chdir(path)
from catalog.models import Service, Price
with open('price.csv') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
p = Price(com_desc=row['com_desc'],
service=Service.objects.filter(cpt=str(row['cpt']))[0])
p.save()
这是我得到的错误:
site-packages/django/db/models/query.py", line 303, in __getitem__
return qs._result_cache[0]
IndexError: list index out of range
数据看起来就像这样: 价格数据:(csv文件中包含标题)
com_des, cpt
"desc 1", '57647'
"desc 2", '87654'
服务数据:(文件中包含标题)
desc_us, cpt, price
"desc1....", '57647', '89.95'
"dsc2.....", '87654', '875.87'
这是models.py 价格
class Price(models.Model):
com_desc = models.CharField(max_length = 200, blank = True, null = True)
service = models.ForeignKey("Service", on_delete=models.SET_NULL, null=True)
服务
class Service(models.Model):
desc_us = models.TextField(blank=True, primary_key = True)
cpt = models.IntegerField(default= 10000)
答案 0 :(得分:0)
您的Service.cpt
是一个整数字段,因此它永远不会与字符串匹配。您应该将row['cpt']
转换为整数以进行过滤:
service=Service.objects.filter(cpt=int(row['cpt']))[0])