【问题标题】:Django multiple querysets paginated as oneDjango多个查询集分页为一个
【发布时间】:2011-11-19 02:29:54
【问题描述】:

您好,我正在构建一个搜索结果页面,它结合了来自多个数据库的多个查询集,我想将它们分页为一组。

在我看来,我有:

def combined_search(request):
    ...
    first_query_set = Mytable_db1.objects.select_related().filter(q)
    first_count = first_query_set.count

    second_query_set = Mytable_db2.objects.select_related().filter(q)
    second_count = second_query_set.count
    # combine querysets
    combined_query_set = list(chain(first_query_set, second_query_set))

    # create a new paginator instance with items-per-page
    paginator = Paginator(combined_query_set, 5)
    # get the page number from a get param if param is blank then set page to 1 
    page = int(request.GET.get('page', '1')) 
    # grab the current page from the paginator...  
    items = paginator.page(page)
    ...

然后在我的模板中我想要类似的东西:

<h1>{{ first_count }} results in mydb1:</h1>
{% for x in first_query_set %}
     <p>{{ x.field }}</p>
{% endfor %}


<h1>{{ second_count }} results in mydb2:</h1>
{% for y in second_query_set %}
     <p>{{ y.field }}</p>
{% endfor %}

问题是我想将两个集合分页,就好像它们是一个集合但包括标题一样。因此,如果第一组只有 2 个结果,第二组只有 18 个结果,那么第一组(包括标题)只会出现在第一页上,第二组还有 3 页。

【问题讨论】:

  • 抱歉,我已经尝试过了,但我仍然无法将整个集合作为模板中的一个进行迭代。请您稍微扩展一下您的答案。谢谢!

标签: django pagination


【解决方案1】:

您需要单独对查询集进行分页,然后将请求中的页码映射到适当的分页器。

类似这样的:

page = int(request.GET.get('page', '1'))
first_set_page_count = math.ceil(first_count / 5)
if page > first_set_page_count:
    page = page - first_set_page_count
    items = second_paginator.page(page)
else:
    items = first_paginator.page(page)

【讨论】:

    猜你喜欢
    • 2013-03-13
    • 1970-01-01
    • 2019-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-02
    • 1970-01-01
    • 2016-05-09
    相关资源
    最近更新 更多