【发布时间】:2019-06-17 00:08:44
【问题描述】:
目前,我的 Django 应用程序有数百万条记录,我想根据它的 ManyToMany 相关字段值进行更新。
因此,我所做的工作有效,但花了很多次。为了只更新三个记录,它使用 13 个查询。
Record 模型具有 genres 字段,即 ManyToMany 字段。此外,还有authors 字段,它也是ManyToMany 字段。
最后,Author 模型有 ManyToMany 字段,表示 genres。
for i in Record.objects.filter(authors__popular=True).only("authors", "genres"):
for a in i.authors.all():
print(a.name) # test purpose
for genre in i.genres.all():
if a.genres.exists():
a.genres.add(genre)
当我运行 len(connection.queries) 时,它会显示运行的查询编号,我希望它小于 13。
【问题讨论】:
标签: django python-3.x django-models django-orm