2

我有一个从 csv 文件导入的导入脚本,但一个值(客户)可以重复。因此,例如名称总是不同的,但客户 (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
4

1 回答 1

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
于 2013-09-17T13:08:03.387 回答