【问题标题】:Efficiently bulk updating many ManyToMany fields有效地批量更新许多 ManyToMany 字段
【发布时间】:2021-09-26 01:53:08
【问题描述】:

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

我正在尝试 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)

批量创建大量 Person 对象后,我想添加该组中谁是朋友的信息。

有没有比遍历每个新人并调用.set(friend_pks).add(*friend_pks) 更有效的方法?

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

【问题讨论】:

    标签: python django postgresql django-models many-to-many


    【解决方案1】:

    好吧,我的帖子还为时过早——看来this 回答了这个问题。

    关键是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, ...])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多