0
第一組python代碼正確導入整個CSV文件。但是,如果我嘗試將ZipMHA模型作爲參數傳遞,它只會導入CSV文件的第一行。有人可以在將模型傳遞給函數時解釋這種行爲變化嗎?將模型類傳遞給函數更改行爲
import csv
from bah_api.models import withDependents, withOutDependents, ZipMHA
# Populate CSV file into model
def LoadCSV(file_location, delim):
f = open(file_location)
csv_f = csv.reader(f, delimiter=delim)
for row in csv_f:
i = 1
# create a model instance
target_model = ZipMHA()
#loop through the rows
for y in row:
setattr(target_model, target_model._meta.fields[i].name, y)
i += 1
# save each row
target_model.save()
f.close()
LoadCSV("BAH2015/sorted_zipmha15.txt", ' ')
模型作爲參數傳遞(只讀取第一行):
# Populate CSV file into model
def LoadCSV(file_location, my_model, delim):
f = open(file_location)
csv_f = csv.reader(f, delimiter=delim)
for row in csv_f:
i = 1
# create a model instance
target_model = my_model
#loop through the rows
for y in row:
setattr(target_model, target_model._meta.fields[i].name, y)
i += 1
# save each row
target_model.save()
f.close()
LoadCSV("BAH2015/sorted_zipmha15.txt", ZipMHA(), ' ')
現在有道理,謝謝! – Casey