如何将多个值导入一个外键值

时间:2013-09-17 12:59:28

标签: python django django-models foreign-keys

我有一个从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

1 个答案:

答案 0 :(得分:0)

首先,您需要使用Customer字段创建新模型nameRoute_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