在外键中使用Django bulk_create对象?

时间:2012-05-29 12:02:14

标签: python django model save

我正在阅读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?

2 个答案:

答案 0 :(得分:6)

尝试手动设置ID。为了防止竞争条件,请确保将该函数包装为单个事务。

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字段或其他自动递增数据库内生成键的表。由于在Django端生成ID,因此批量创建不会增加密钥。

答案 1 :(得分:2)

对于第一个问题,不会有你无法做到这一点,因为obj将不会设置其主键,因此无法用作外键。

第二个问题,不,这根本不是它所说的。它特别提到“多表继承”:从抽象模型继承不是多表继承。