我有一个从csv文件导入的导入脚本,但一个值(customer)可以重复。例如,名称总是不同的,但是客户(john)可以有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发布于 2013-09-17 21:08:03
首先,您需要创建一个带有name字段的新模型Customer,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 rowhttps://stackoverflow.com/questions/18850572
复制相似问题