我有一个从csv文件导入的导入脚本,但是一个值(customer)可以重复。因此,例如名称将始终不同,但客户(约翰)可以有5个条目。我需要将其导入名为customer的外键以供其他用途。但我不知道如何去做。
我的模特
class Route_destinguisher(models.Model):
name = models.CharField(max_length=100)
customer = models.CharField(max_length=100)
comment = models.TextField(blank=True)
active = models.BooleanField(default=True)
rd = models.CharField(max_length=20, default='33763:264')
def __unicode__(self):
return self.name
我的导入代码
dataReader = csv.reader(open(csv_filepathname), delimiter=',', quotechar='"')
for row in dataReader:
route_distinguisher = Route_destinguisher()
route_distinguisher.customer=row[2].split("-")[0]
route_distinguisher.name=row[2]
route_distinguisher.rd=row[1].replace('\t',':')
route_distinguisher.save()
print row
答案 0 :(得分:0)
首先,您需要使用Customer
字段创建新模型name
,Route_destinguisher
模型应具有Customer
的外键:
class Customer(models.Model):
name = models.CharField(max_length=100)
class Route_destinguisher(models.Model):
name = models.CharField(max_length=100)
customer = models.ForeignKey(Customer)
comment = models.TextField(blank=True)
active = models.BooleanField(default=True)
rd = models.CharField(max_length=20, default='33763:264')
def __unicode__(self):
return self.name
然后,在导入csv时在循环中使用get_or_create():
dataReader = csv.reader(open(csv_filepathname), delimiter=',', quotechar='"')
for row in dataReader:
route_distinguisher = Route_destinguisher()
route_distinguisher.customer = Customer.objects.get_or_create(name=row[2].split("-")[0])
route_distinguisher.name = row[2]
route_distinguisher.rd = row[1].replace('\t',':')
route_distinguisher.save()
print row