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

后端 未结 3 2148
野趣味
野趣味 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条回答
  •  -上瘾入骨i
    2021-02-10 12:43

    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)
    

    Documentation here and here.

提交回复
热议问题