This is my view code. I iterate over all the entries in DB and when rollno matches, I want to store the student name for previous,current and next student in one go. Is there any way to implement it?
if request.method == 'POST':
rollno = request.POST.get('roll',None)
studentlist = Students.objects.all()
for st in studentlist:
if st.roll_no == rollno:
If I understood you correctly this is what you want
# create generator that will provide you with 3 neighobring students at the same time def student_gen(): triple =  for s in Students.objects.all(): triple.append(s) if len(triple) == 3: yield triple triple.pop(0) # and inside your view ... if request.method == 'POST': rollno = request.POST.get('roll',None) for three_students in student_gen(): if three_students.roll_no == rollno: break print(three_students)