【发布时间】:2015-06-26 02:17:42
【问题描述】:
第一组 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(), ' ')
【问题讨论】: