Wagtail: Get previous or next sibling

Django-Treebeard provides get_next_sibling and get_prev_sibling which will return your direct siblings in the tree, but these are not necessarily your next published sibling. To request those you can use:

prev = page.get_prev_siblings().live().first()
next = page.get_next_siblings().live().first()

Which can obviously also be chained with any other queryset operations.


After going through the debugger for a while, I found out that wagtail already has two methods: get_prev_sibling() and get_next_sibling().

So the methods could look like this (accounting for the first page in the previous method and the last item in the next method):

def prev_portrait(self):
    if self.get_prev_sibling():
        return self.get_prev_sibling().url
    else:
        return self.get_siblings().last().url

def next_portrait(self):
    if self.get_next_sibling():
        return self.get_next_sibling().url
    else:
        return self.get_siblings().first().url