如何从过滤的有序查询器中获取上一个和下一个对象? [英] How can I get previous and next objects from a filtered, ordered queryset?

查看:91
本文介绍了如何从过滤的有序查询器中获取上一个和下一个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基于模型对象的页面,我想要链接到上一页和下一页。我不喜欢我目前的解决方案,因为它需要评估整个查询(获取 ids 列表),然后再两个获取查询。当然有一些方法可以在一次通过?

I have a page based on a model object, and I want to have links to the previous and next pages. I don't like my current solution because it requires evaluating the entire queryset (to get the ids list), and then two more get queries. Surely there is some way this can be done in one pass?

def get_prev_and_next_page(current_page):
    ids = list(Page.objects.values_list("id", flat=True))
    current_idx = ids.index(current_page.id)
    prev_page = Page.objects.get(id=ids[current_idx-1])
    try:
        next_page = Page.objects.get(id=ids[current_idx+1])
    except IndexError:
        next_page = Page.objects.get(id=ids[0])
    return (prev_page, next_page)

排序顺序在模型中定义,所以不必在这里处理,但请注意,您不能假设ids是顺序的。

Sort order is defined in the model, so doesn't have to be handled here, but note that you can't assume that ids are sequential.

推荐答案

声音像Paginator设置为1的阈值的东西就会很好。

Sounds like something the Paginator set to a threshold of 1 would do well at.

# Full query set...
pages = Page.objects.filter(column=somevalue)
p = Paginator(pages, 1)

# Where next page would be something like...
if p.has_next():
     p.page(p.number+1)

这里的文档 here

这篇关于如何从过滤的有序查询器中获取上一个和下一个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆