【问题标题】:Python TypeError: 'AutoField' object is not iterablePython TypeError:“AutoField”对象不可迭代
【发布时间】:2018-05-01 09:11:29
【问题描述】:

我正在尝试将 Django 模型实例中的字段值写入 csv 文件,并且我正在使用以下代码,其中 image 是模型 Image 的一个实例。我正在尝试这样做,但没有具体命名字段名称。

    with open(output_file, "a") as outfile:
        writer = csv.writer(outfile)
        writer.writerow([item.value for item in image._meta.get_field(field.name)] for field in image._meta.get_fields())
        #writer.writerow([field.name for field in Image._meta.get_fields()])
    outfile.close()

当我使用注释掉的行时,我得到了我所期望的字段名称。我现在正在尝试获取实际的字段值,并且我得到了新的 writerow

这是给我的

TypeError: 'AutoField' 对象不可迭代

【问题讨论】:

    标签: python django python-3.5 export-to-csv


    【解决方案1】:

    我不知道为什么你有一个双 for 循环。 image._meta.get_field(field.name) 返回一个字段,所以你不能循环遍历它。

    一旦有了字段名称,您就可以使用getattr 来获取该字段的值。也许你想要这样的东西:

        writer.writerow([getattr(image, field.name) for field in image._meta.get_fields()])
    

    【讨论】:

    • item 更改为image,即实例。
    • 好地方,已修复:)
    猜你喜欢
    • 2021-12-13
    • 2015-04-06
    • 2013-10-31
    • 2017-08-29
    • 2018-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多