在for循环中,python访问数据库中的下一个对象 [英] python-accessing the next object in database while in for loop
本文介绍了在for循环中,python访问数据库中的下一个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的视图代码。我迭代了DB中的所有条目,当rollno匹配时,我想一次存储上一个,当前和下一个学生的学生名称。有没有办法实现?
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*]
推荐答案
理解你正确的这是你想要的
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)
这篇关于在for循环中,python访问数据库中的下一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文