如何将CSV数据导入Django模型

我有一些CSV数据,我想使用示例CSV数据导入django模型:

1;"02-01-101101";"Worm Gear HRF 50";"Ratio 1 : 10";"input shaft, output shaft, direction A, color dark green";

2;"02-01-101102";"Worm Gear HRF 50";"Ratio 1 : 20";"input shaft, output shaft, direction A, color dark green";

3;"02-01-101103";"Worm Gear HRF 50";"Ratio 1 : 30";"input shaft, output shaft, direction A, color dark green";

4;"02-01-101104";"Worm Gear HRF 50";"Ratio 1 : 40";"input shaft, output shaft, direction A, color dark green";

5;"02-01-101105";"Worm Gear HRF 50";"Ratio 1 : 50";"input shaft, output shaft, direction A, color dark green";

我有一些名为Product的django模型。在产品还有像一些领域namedescriptionprice。我想要这样的东西:

product=Product()

product.name = "Worm Gear HRF 70(02-01-101116)"

product.description = "input shaft, output shaft, direction A, color dark green"

product.price = 100

回答:

你想使用python语言中的csv模块,并且应该使用Django的get_or_create方法

 with open(path) as f:

reader = csv.reader(f)

for row in reader:

_, created = Teacher.objects.get_or_create(

first_name=row[0],

last_name=row[1],

middle_name=row[2],

)

# creates a tuple of the new object or

# current object and a boolean of if it was created

在我的示例中,模型老师具有三个属性first_name,last_name和middle_name。

以上是 如何将CSV数据导入Django模型 的全部内容, 来源链接: utcz.com/qa/428235.html

回到顶部