在Django中导入csv

时间:2018-11-28 09:07:44

标签: python django database django-models

我正在尝试从manage.py shell导入csv文件到db,但这给了我错误

import csv
with open(r"C:\Users\yousa\Desktop\xp\exp\Dist_Extended_TissuesWise_ClusteredAnnotated_21nov2018_qaz.csv", 'r') as f:
        reader = csv.reader(f)
        lines = list(reader)
        del lines[0]
        objects = []
        for line in lines:
            obj =Maize_clustert()
            obj.chromosome = int(line[0])
            obj.cluster_start = int(line[1])
            obj.cluster_end = int(line[2])
            obj.strand = line[3]
            obj.pac = int(line[4])
            obj.pac_suppoort = int(line[5])
            obj.cluster_support = int(line[6])
            obj.region = line[7]
            obj.gene_id = line[8]
            obj.transcript_id = line[9]
            obj.distance = line[10]
            obj.transcript_code = line[11]
            obj.gene_cord = line[12]
            obj.utr_length = int(line[13])
            obj.gene_biotype = line[14]
            obj.cluster_size = int(line[15])
            obj.number_pas = int(line[16])
            obj.zygote = int(line[17])
            obj.sperm = int(line[18])
            obj.egg = int(line[19])
            obj.root = int(line[20])
            obj.embryo = int(line[21])
            obj.basal = int(line[22])
            obj.ear = int(line[23])
            obj.apical = int(line[24])
            obj.ovule = int(line[24])
            objects.append(obj)
        Maize_clustert.objects.bulk_create(objects)

在manage.py shell中运行此代码时,它会给我结果

Traceback (most recent call last):
  File "<input>", line 8, in <module>
NameError: name 'Maize_clustert' is not defined

在models.py中,我创建了我的数据的完整模型 有没有其他选择或我做错了 请帮助我

2 个答案:

答案 0 :(得分:1)

仔细阅读信息:

NameError: name 'Maize_clustert' is not defined

这意味着在执行CSV读取的文件中未定义此类。因此,即使在模型.py中也存在Maize_clustert,您也必须将其导入使用它的文件中。

基本上将其添加到文件顶部:

`from application.models导入Maize_clustert

答案 1 :(得分:0)

您需要在文件中导入Maize_clustert。喜欢:

# Please read the PEP-8 Style Guide on Naming convention
# Class Name should be 'PascalCase'
from yourapp.models import Maize_clustert