user37886 user37886 - 1 month ago 6
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:
three_students=[*prev_student,current_student,next_student*]

Answer

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[1].roll_no == rollno:
            break
    print(three_students)