【问题标题】:Is is possible to decrease connection that made to db?是否可以减少与数据库的连接?
【发布时间】: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


    【解决方案1】:

    到目前为止,我只是将 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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-20
      • 2014-02-28
      • 2012-01-08
      • 2015-05-13
      • 1970-01-01
      • 1970-01-01
      • 2012-07-27
      • 2015-03-31
      相关资源
      最近更新 更多