首页 > 解决方案 > 有效地批量更新许多 ManyToMany 字段

问题描述

这个问题的一个版本在这里被问了好几次,但没有一个提供的答案能解决我的确切问题。

我正在尝试bulk_create使用一个ManyToMany字段的模型的一批对象。

在这种情况下,该ManyToMany字段指的是同一模型,尽管我也对一般情况感兴趣。

假设这是我的模型:

class Person(models.Model):
    name = models.CharField(max_length=20, blank=True, null=True)
    friends = models.ManyToMany("self", related_name="friends_with", null=True)

在 bulk_creating 大量 Person 对象之后,我想在这个组中添加谁是朋友的信息。

有没有比遍历每个新 Person 并调用.set(friend_pks)or更有效的方法来解决这个问题.add(*friend_pks)

即,bulk_update 的类似物。with transaction.atomic()通过将循环包装到(来自this answer)中,我已经实现了一些加速,但它仍然很慢。

标签: pythondjangopostgresqldjango-modelsmany-to-many

解决方案


好的,我的帖子还为时过早——这似乎回答了这个问题。

关键是bulk_create通过模型。在这个例子中:

friends_relation_1 = Person.friends.through(from_person_id=1, to_person_id=2)
friends_relation_2 = Person.friends.through(from_person_id=2, to_person_id=8)

Person.friends.through.objects.bulk_create([friends_relation_1, friends_relation_2, ...])

推荐阅读