Django 1.7 - 使用bulk_create插入模型数据然后保存

时间:2015-03-26 17:53:28

标签: python django django-models

我在迁移文件中有一个自定义方法,用于创建模型对象列表(使用从匹配的JSON对象列表派生的值),并使用bulk_create将此列表插入到模型中。代码如下所示:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

def populate_db( apps, schema_editor ):

    mymodel = apps.get_model( 'myapp', 'mymodel' )
    db_alias = schema_editor.connection.alias

    mymodel_objs = [<obj1>,<obj2>,...,<objn>]
    mymodel.objects.using( db_alias ).bulk_create( mymodel_objs )
    mymodel.save()

但是我遇到了以下运行时错误:

mymodel.save()
TypeError: unbound method save() must be called with mymodel instance as first argument (got nothing instead)

文档说bulk_create不会将数据保存到数据库中,如何只使用一个查询来实现这一点,这是bulk_create的假设优势?

1 个答案:

答案 0 :(得分:3)

bulk_create 执行将数据保存到数据库。使用save()的警告意味着不会为每个实例调用模型的save方法,因此如果您使用任何特殊逻辑覆盖模型的save方法,则不会执行它。在您的情况下,您可以删除Model.save()行

相关问题