view raw
user37886 user37886 - 6 months ago 38
Python Question

python-accessing the next object in database while in for loop

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():
        if len(triple) == 3:
            yield triple

# 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: