If the database is self increasing ID, It's easy to get the previous and next records :
Obj = models.Article.objects.get(id=id)
prev = models.Article.objects.get(id = id-1)
next = models.Article.objects.get(id = id+1)
But I was When building data tables , Forget to add auto increment ID 了 , We had to find another way .
At present, we have found a very wonderful way , Share with you :
Install first django-next-prev package :
pip install django-next-prev
Then introduce the :
from next_prev import next_in_order,prev_in_order
obj = models.Article.objects.get(...)
next = next_in_order(obj)
prev = prev_in_order(obj)
You can get the list from other fields , Then get the previous and next data :
objs = modes.Article.objects.filter(list=abcde)
obj = objs.get(...)
next = next_in_order(obj,qs=objs)
prev = prev_in_order(obj,qs=objs)
Successfully obtain the previous and next objects .