我有一些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";
我有一些叫产品的django模型。在产品中有一些字段,如name
、description
和price
。我想要这样的东西:
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
您希望使用csv模块,它是python语言的一部分,您应该使用Django的get_或_create方法
在我的示例中,模范教师有三个属性first_name、last_name和middle_name。
关于get_or_create method的Django文档
如果你想使用一个库,在google上快速搜索
csv
和django
会发现两个库-django-csvimport和django-adaptors。让我们看看他们对自己的看法。。。第一个要求您编写一个模型来匹配csv文件,而第二个则更像是一个命令行导入程序,这在您使用它们的方式上是一个巨大的差异,而且每一个都适合不同类型的项目。
那该用哪一个呢?这取决于从长远来看哪一个更适合您的项目。
但是,您也可以通过编写own django script来导入csv文件,从而完全避免使用库,大致如下(警告,前面是伪代码):
太简单了。见鬼,如果是一次性导入,可以通过django s Hell进行交互。只需-找出你想对你的项目做什么,你需要处理多少文件,然后-如果你决定使用一个库,试着找出哪一个更适合你的需要。
Pythoncsv library可以进行解析,代码可以将它们转换成
Products()
。相关问题 更多 >
编程相关推荐