是否可以减少与数据库的连接?
Is is possible to decrease connection that made to db?
目前,我的 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。
到目前为止,我只是将 1 条记录的查询数量减少到 1。这就是我取得的成就
for i in Author.objects.annotate(record_count=Count('record'), record_genres=ArrayAgg('record__genres', distinct=True):
if i.record_count > 0 and i.record_genres:
i.genres.set(i.record_genres)
i.save()
目前,我的 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。
到目前为止,我只是将 1 条记录的查询数量减少到 1。这就是我取得的成就
for i in Author.objects.annotate(record_count=Count('record'), record_genres=ArrayAgg('record__genres', distinct=True):
if i.record_count > 0 and i.record_genres:
i.genres.set(i.record_genres)
i.save()