How can I get previous and next objects from a filtered, ordered queryset?

后端 未结 3 2149
野趣味
野趣味 2021-02-10 12:15

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 query

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-10 12:53

    Check out django-next-prev, I wrote it to solve this exact problem. In this case:

    from next_prev import next_in_order, prev_in_order
    
    def get_prev_and_next_page(current_page):
        page_qs = Page.objects.all()  # this could be filtered, or ordered
        prev_page = prev_in_order(current_page, page_qs)
        next_page = next_in_order(current_page, page_qs)
        return (prev_page, next_page)
    

提交回复
热议问题