csv导入django模型

时间:2017-11-13 19:21:59

标签: python django

我的python csv导入脚本每次加载数据时都会在数据库模型中创建一个额外的空条目。我试过各种方法,但我仍然得到一个空条目加上从csv加载的实际数据。这是我的脚本的样子。请你的帮助将取得很大的成就。

application/x-www-form-urlencoded

2 个答案:

答案 0 :(得分:1)

除了bulk_create

之外,您似乎正在初始化并保存一个空实例
 # This line shouldn't be needed
 attendee_instance = Attendee()
 Attendee.objects.bulk_create(
      [Attendee(firstname=row[0],
           surname=row[1],
           email=row[2],
       )
       for row in reader])

# Nor should this line.
attendee_instance.save()

答案 1 :(得分:1)

你的问题出在这个(裁剪的)部分:

attendee_instance = Attendee()

Attendee.objects.bulk_create(
                [Attendee(firstname=row[0],
                          surname=row[1],
                          email=row[2],
                          )
attendee_instance.save()

使用第一个attendee_instance,您将创建一个空白Attendee对象。您稍后使用attendee_instance.save()保存此空白对象。

中间的行 - Attendee.objects.bulk_create... - 您将单个项目列表传递给bulk_create,因此它会在那里创建对象(带有数据)。你不需要两者。

你想要的可能是:

Attendee.objects.create(firstname=row[0],
                          surname=row[1],
                          email=row[2],
                          )

除非您创建多个对象,否则不需要bulk_create,您可以直接使用create。同样,您不需要按attendee_instance=Attendee()创建对象,然后手动更改属性,如上所述,您可以一次完成所有操作。

值得注意的是caveats on the limitations of bulk create,特别是如果你没有使用Postgres,以及你是否已经到了使用post_savepre_save信号的地步。 create方法 会触发这些保存信号,因此请确保为您的用例使用最合适的保存信号