python - 有效地批量更新许多 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)中,我已经实现了一些加速,但它仍然很慢。
解决方案
好的,我的帖子还为时过早——这似乎回答了这个问题。
关键是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, ...])
推荐阅读
- ios - 如何在 xcode 中从外部视图进行 Segue
- azure - Azure DevOps 的 Azure 部署找不到 zip 包
- bash - 比较 Html 页面中两个几乎相等的字符串
- django - 如何在 apiview 类中使用(别名)在查询集中设置变量的值
- javascript - 无法理解在 Reactjs 中使用 app.logger.getLogger() 的函数
- java - FlinkCEP 中的 AfterMatchSkipStrategy 未应用
- java - 在 Java8 中收集统计信息
- javascript - 如何使用 JavaScript 中的正则表达式格式化包含在内容字符串中的货币?
- scala - 不清楚的编译信息 seqDerivedOrdering 不是 scala.math.Ordering[W] 的有效隐式值
- c# - 禁用/启用网络连接后多播套接字未接收