Django ORM bulk_create 1:1 相关模型

Django ORM bulk_create 1:1 related models

我见过类似的问题,但提供的答案含糊不清,因此我将不胜感激任何反馈。

我想对一些相关的 1:1 对象进行批量创建。

我希望我能做这样的事情:

class A(models.Model):

class B(models.Model):
    A = models.ForeignKey(A)

all_a = []
all_b = []
for i in range(10000):
    new_a = A()
    new_b = B(A=new_a)
    all_a.append(new_a)
    all_b.append(new_b)

with transaction.atomic():
    A.objects.bulk_create(all_a)
    B.objects.bulk_create(all_b)

但我猜想 A 模型需要先写入数据库,然后返回实际 PK 并与 B 模型关联,然后才能写入它们。

有没有人对如何有效地执行此操作有好的建议? 提前致谢

是的,您需要事先创建 A 实例。像这样尝试:

all_a = []
all_b = []
new_a_list = []

for i in range(10000):
    new_a = A()
    all_a.append(new_a)
with transaction.atomic():
    new_a_list = A.objects.bulk_create(all_a)

for new_a in new_a_list:
    new_b = B(A=new_a)
    all_b.append(new_b)

with transaction.atomic():
    B.objects.bulk_create(all_b)

在 PostgreSQL 上这很简单,因为 bulk_create() for A will populate 每个对象的 pk.

with transaction.atomic():
    all_a = [A() for _ in range(1000)]
    A.objects.bulk_create(all_a)

    all_b = [B(A=new_A) for new_a in all_a]
    B.objects.bulk_create(all_b)

在其他数据库上,这会更加棘手,因为 bulk_create() doesn't get the ids 个新创建的对象。

If the model’s primary key is an AutoField it does not retrieve and set the primary key attribute, as save() does, unless the database backend supports it (currently PostgreSQL).