如何将CSV文件导入django模型

时间:2016-10-10 16:43:55

标签: python django csv graph

我有像这样的Django模型

class Revo(models.Model):           
    SuiteName = models.CharField(max_length=255)
    Test_Case = models.CharField(max_length=255)
    FileName = models.CharField(max_length=255)
    Total_Action = models.CharField(max_length=255)
    Pass = models.CharField(max_length=255)
    Fail = models.CharField(max_length=255)
    Exe_Time = models.CharField(max_length=255)
    Result = models.CharField(max_length=255)
    create_date = models.DateTimeField(default=datetime.datetime.now)

    class Meta:
        verbose_name_plural = "Revo"

我有像这样的CSV文件

SuiteName,Test Case,FileName,Total Action,Pass,Fail,Exe Time,Result
DEMO_TEST_SUITE,Testcase 1,file1,82,0,108,0:27:52,FAIL
DEMO_TEST_SUITE,Testcase 2,file2,86,0,108,0:27:52,FAIL
DEMO_TEST_SUITE,Testcase 3,file3,820,0,108,0:27:52,FAIL
DEMO_TEST_SUITE,Testcase 4,file4,182,0,108,0:27:52,FAIL
DEMO_TEST_SUITE,Testcase 5,file5,102,0,108,0:27:52,FAIL
DEMO_TEST_SUITE,Testcase 6,file6,111,0,108,0:27:52,FAIL

如何将此csv数据导入我的django模型?另外,有没有办法直接从数据库中绘制出这些数据?

1 个答案:

答案 0 :(得分:2)

您可以使用内置的csv module将您的csv文件转换为dict like object

import csv

with open('import.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        # The header row values become your keys
        suite_name = row['SuiteName']
        test_case = row['Test Case']
        # etc....

        new_revo = Revo(SuiteName=suite_name, TestCase=test_case,...)
        new_revo.save()