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>Assuming <code>roll_no</code> is incremental then you can just use <code>__in</code></p>

<pre><code>Student.objects.filter(roll_no__in=[roll_no - 1, roll_no, roll_no + 1])
</code></pre>

<p>If you can't guarrantee they're always incremental then you may need a separate query first to get the roll_no's you're trying to find first.</p>

<p>For example (without error/out of bounds handling),</p>

<pre><code>rolls = Student.objects.order_by('roll_no').values_list('roll_no', flat=True)
idx = rolls.index(rollno)

rolls_to_filter_on = rolls[idx-1:3]
</code></pre>

python django