我正在阅读Django bulk_create和它的一些“缺陷”:
"
This has a number of caveats though:
1. The model's save() method will not be called, and the pre_save and post_save signals will not be sent.
2. It does not work with child models in a multi-table inheritance scenario.
3. If the model's primary key is an AutoField it does not retrieve and set the primary key attribute, as save() does.
"我没有完全理解它。所以,如果我有一个对象列表,就把它传递给bulk_create:
objList = [a, b, c,] #none are saved
model.objects.bulk_create(objList)我仍然可以在外键中使用这些对象吗?
for obj in objList:
o = otherModel(something='asdfasdf', fkey=obj)
o.save() # will this be fine given the caveats stated above?那么foreignKey关系还好吗?另外,当它说2.它不适用于多表继承场景中的子模型时,这意味着任何从另一个模型(抽象或非抽象)继承的模型都不能使用bulk_create?
发布于 2012-10-31 00:04:12
尝试手动设置ids。为防止出现争用情况,请确保将函数包装为单个事务。
from django.db import transaction, models
@transaction.commit_on_success
def bulk_create_with_manual_ids(foo_list):
id_start = (Foo.objects.all().aggregate(models.Max('id'))['id__max'] or 0) + 1
for i,foo in enumerate(foo_list): foo.id = id_start + i
return Foo.objects.bulk_create(foo_list)
objList = [Foo(),Foo(),Foo()]
foo_objects = bulk_create_with_manual_ids(objList)
Bar(foo=foo_objects[0]).save()请注意,这种方法不适合任何具有serial字段或其他自动递增的数据库内生成的键的表。由于ID是在Django端生成的,所以批量创建不会增加密钥。
发布于 2012-05-29 20:14:26
对于第一个问题,您不能这样做,因为obj不会设置其主键,因此不能用作外键。
第二个问题,不,这根本不是它所说的。它特别提到了“多表继承”:从抽象模型继承不是多表继承。
https://stackoverflow.com/questions/10798767
复制相似问题