Django 1.7 - 使用 bulk_create 插入模型数据然后保存
Django 1.7 - inserting model data using bulk_create and then saving
我在迁移文件中有一个自定义方法,它创建一个模型对象列表(具有从匹配的 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
的优点?
bulk_create 是否 将数据保存到数据库中。 save() 的警告意味着不会为每个实例调用模型的 save 方法,因此如果您使用任何特殊逻辑覆盖了模型的 save 方法,它将不会被执行。在您的情况下,您只需删除 Model.save() 行
我在迁移文件中有一个自定义方法,它创建一个模型对象列表(具有从匹配的 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
的优点?
bulk_create 是否 将数据保存到数据库中。 save() 的警告意味着不会为每个实例调用模型的 save 方法,因此如果您使用任何特殊逻辑覆盖了模型的 save 方法,它将不会被执行。在您的情况下,您只需删除 Model.save() 行