【问题标题】:Passing model class to function changes behavior将模型类传递给函数会改变行为
【发布时间】: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(), ' ')

【问题讨论】:

    标签: python django csv


    【解决方案1】:

    您传递的是模型实例而不是模型类。 target_model 实例的创建应该是这样的:

    target_model = my_model() # note the round brackets
    

    并在ZipMHA类名之后调用不带括号的函数:

    LoadCSV("BAH2015/sorted_zipmha15.txt", ZipMHA, ' ')
    

    【讨论】:

      猜你喜欢
      • 2021-09-26
      • 2017-04-15
      • 2014-04-03
      • 1970-01-01
      • 2016-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多