Django Select 与模板分页搜索结果相关以减少查询?

Django Select Related in Template Paginated Search Results to Reduce Queries?

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

理想情况下,我试图将查询减少到产品本身的数量 -- 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)
        })

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

select_related 仅适用于外键。对于多对多字段,您可以使用 prefetch_related。我认为与 prefect related 你必须指定你想要获取的相关模型,并且你不能在没有像 select_related.

这样的参数的情况下调用它

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