如何导入csv数据到django模型 [英] how to import csv data into django models

查看:1203
本文介绍了如何导入csv数据到django模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  1;02 -01-101101;蜗轮HRF 50;比例1:10;输入轴,输出轴,方向A,颜色深绿色; 
2;02-01-101102;蜗轮HRF 50;比例1:20;输入轴,输出轴,方向A,颜色深绿色;
3;02-01-101103;蜗轮HRF 50;比例1:30;输入轴,输出轴,方向A,颜色深绿色;
4;02-01-101104;蜗轮HRF 50;比例1:40;输入轴,输出轴,方向A,颜色深绿色;
5;02-01-101105;蜗轮HRF 50;比例1:50;输入轴,输出轴,方向A,颜色深绿色;

我有一些名为Product的django模型。在产品中有一些字段例如 name description price 。我想要这样的:

  product = Product()
product.name =Worm Gear HRF 70 -01-101116)
product.description =输入轴,输出轴,方向A,颜色深绿色
product.price = 100
pre>

解决方案

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



  csv.reader(f)
在阅读器中的行:
_,created = Teacher.objects.get_or_create(
first_name = row [0],
last_name = row [1] ,
middle_name = row [2],

#创建一个新对象的元组或
#当前对象和一个布尔值如果它被创建

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



Django文档 get_or_create方法


I have some CSV data and I want to import into django models using the example CSV data:

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";

I have some django models named Product. In Product there are some fields like name, description and price. I want something like this:

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

解决方案

You want to use the csv module that is part of the python language and you should use Django's get_or_create method

 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

In my example the model teacher has three attributes first_name, last_name and middle_name.

Django documentation of get_or_create method

这篇关于如何导入csv数据到django模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆