[Answer]-Get previous and next object in sequence in Django – what is most efficient?

1👍

A possible solution is the following method in the Box model:

def get_ordering(self):
   try:
       top = Box.models.filter(number__lt=self.number).order_by('-number')[0]
   except IndexError:
       top = None

   try:
       bottom = Box.models.filter(number__gt=self.number).order_by('number')[0]
   except IndexError:
       top = None

   return top,bottom

However, a better solution would be to use django-mptt an implementation of tree traversal for django.

Leave a comment