【问题标题】:Django Select Related in Template Paginated Search Results to Reduce Queries?Django 在模板分页搜索结果中选择相关以减少查询?
【发布时间】:2015-11-04 07:56:50
【问题描述】:

我有一个模型(产品),它实际上包含许多多对多字段。

理想情况下,我会尝试将查询减少到产品本身的数量——25 个,但考虑到外键和 m2ms 的深度,我知道这可能是不可能的。但我仍然在争取最好的结果。

这是我的看法:

def index(request):
    products = Product.objects.select_related()
    paginator = Paginator(products, 25) 
    page = request.GET.get('page')

    try:
        products = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        products = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        products = paginator.page(paginator.num_pages)

    print (len(connection.queries))
    return render(request, 'editor-index.html', {
        'products': products, 
        'connection':connection,
        'csrf':csrf(request)
        })

如何减少其中的查询?最好预取与产品相关的所有数据。这样的事情可能吗?

【问题讨论】:

    标签: python django templates model psql


    【解决方案1】:

    select_related 仅适用于外键。对于多对多字段,您可以使用prefetch_related。我认为与完美相关你必须指定你想要获取的相关模型,并且你不能在没有像select_related这样的参数的情况下调用它。

    请注意,您不需要对 25 种产品进行 25 次查询。应该可以将其减少为针对 products 查询集的一个查询、针对每个 prefetch_related 参数的一个额外查询以及(因为您使用的是分页器)针对对象总数的一个查询。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-06
      • 2014-02-07
      • 2019-10-01
      • 2021-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多