在外键中使用Django的bulk_create对象?

2024-01-16

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


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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在外键中使用Django的bulk_create对象? 的相关文章

随机推荐