在外键中使用Django bulk_create对象?

Der*_*rek 10 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.
"
Run Code Online (Sandbox Code Playgroud)

我没有完全理解它.所以,如果我有一个对象列表,请将其传递给bulk_create:

objList = [a, b, c,] #none are saved
model.objects.bulk_create(objList)
Run Code Online (Sandbox Code Playgroud)

我还能在外键中使用这些对象吗?

for obj in objList:
    o = otherModel(something='asdfasdf', fkey=obj)
    o.save() # will this be fine given the caveats stated above?
Run Code Online (Sandbox Code Playgroud)

那么foreignKey关系会好吗?当它说2.它不适用于多表继承场景中的子模型时,它意味着任何继承自另一个模型(抽象与否)的模型都不能使用bulk_create?

ega*_*fni 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()
Run Code Online (Sandbox Code Playgroud)

请注意,此方法不适用于具有serial字段或其他自动递增数据库内生成密钥的任何表.由于在Django端生成ID,因此批量创建不会增加密钥.

  • 我已经投票但我应该投票!id字段不会在数据库中自动增量.这是一个很大的问题. (4认同)

Dan*_*man 3

对于第一个问题,不,您将无法这样做,因为obj没有设置主键,因此无法用作外键。

第二个问题,不,根本不是这个意思。其中特别提到了“多表继承”:从抽象模型继承并不是多表继承。

  • 那么您建议如何处理单独保存时的性能问题? (9认同)