第一组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(), ' ')
答案 0 :(得分:2)
您正在传递模型实例而不是模型类。创建target_model
实例应该是这样的:
target_model = my_model() # note the round brackets
在ZipMHA
班级名称后调用不带括号的函数:
LoadCSV("BAH2015/sorted_zipmha15.txt", ZipMHA, ' ')