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)
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.