gpt4 book ai didi

python - 在外键中使用 Django bulk_create 对象?

转载 作者:太空狗 更新时间:2023-10-29 18:31:47 24 4
gpt4 key购买 nike

我正在阅读 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. It does not work with child models in a multi-table inheritance scenarios 时,这意味着任何从另一个模型(抽象或非抽象)继承的模型都不能使用 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 端生成的,因此批量创建不会增加 key 。

关于python - 在外键中使用 Django bulk_create 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10798767/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com