python-accessing the next object in database while in for loop
<p>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?</p>

<pre><code>if request.method == 'POST':
        rollno = request.POST.get('roll',None)
        studentlist = Students.objects.all()
        for st in studentlist:
          if st.roll_no == rollno:
             three_students=[*prev_student,current_student,next_student*]
</code></pre>

<p>If I understood you correctly this is what you want</p>

<pre><code># create generator that will provide you with 3 neighobring students at the same time
def student_gen():
    triple = []    
    for s in Students.objects.all():
        if len(triple) == 3:
            triple.pop(0)
            triple.append(s)
            yield triple
        else:
            triple.append(s)

# and inside your view
...
if request.method == 'POST':
    rollno = request.POST.get('roll',None)
    for three_students in student_gen():
        if three_students[1].roll_no == rollno:
            break
    print(three_students)
</code></pre>

python django