如何将CSV数据导入Django模型

2024-06-09 13:15:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些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模型。在产品中有一些字段,如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

Tags: csv数据djangoinputoutputgreenproductcolor
3条回答

您希望使用csv模块,它是python语言的一部分,您应该使用Django的get_或_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。

关于get_or_create method的Django文档

如果你想使用一个库,在google上快速搜索csvdjango会发现两个库-django-csvimportdjango-adaptors。让我们看看他们对自己的看法。。。

  • django适配器:

Django adaptor is a tool which allow you to transform easily a CSV/XML file into a python object or a django model instance.

  • django importsv

django-csvimport is a generic importer tool to allow the upload of CSV files for populating data.

第一个要求您编写一个模型来匹配csv文件,而第二个则更像是一个命令行导入程序,这在您使用它们的方式上是一个巨大的差异,而且每一个都适合不同类型的项目。

那该用哪一个呢?这取决于从长远来看哪一个更适合您的项目。

但是,您也可以通过编写own django script来导入csv文件,从而完全避免使用库,大致如下(警告,前面是伪代码):

# open file & create csvreader
import csv, yada yada yada

# import the relevant model
from myproject.models import Foo

#loop:
for line in csv file:
     line = parse line to a list
     # add some custom validation\parsing for some of the fields

     foo = Foo(fieldname1=line[1], fieldname2=line[2] ... etc. )
     try:
         foo.save()
     except:
         # if the're a problem anywhere, you wanna know about it
         print "there was a problem with line", i 

太简单了。见鬼,如果是一次性导入,可以通过django s Hell进行交互。只需-找出你想对你的项目做什么,你需要处理多少文件,然后-如果你决定使用一个库,试着找出哪一个更适合你的需要。

Pythoncsv library可以进行解析,代码可以将它们转换成Products()

相关问题 更多 >