2016-10-10 163 views
1

我有Django模型這樣如何導入CSV文件,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

您可以使用內置的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()