python - 如何将csv数据导入django模型

标签 python django csv django-models export

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

get_or_create method 的 Django 文档

关于python - 如何将csv数据导入django模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2459979/

相关文章:

python - 在 Pandas 数据帧上运行 sql 查询

pythonic方式打印数据库中的列条件(psql)

python - Django:从 HTML 获取列表数据,无需表单或模型

python - 如何修改 CSV 文件中的数据并更改行和列?

python - 'import ... as' 的约定

django - 无法备份我的 PostgreSQL 数据库 [用户 "USER"的对等身份验证失败]

django - 我可以在 django 中设置多个静态根吗?

Python - 来自 CSV 文件的字典,每个键有多个值

python - python中用逗号分隔数字

python - 如何将理解与 python 中的ordereddict结合起来?