这是我的观看代码。我遍历数据库中的所有条目,当rollno匹配时,我想一次性存储上一个,当前和下一个学生的学生姓名。有没有办法实现它?
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*]
答案 0 :(得分:0)
假设roll_no
是增量版,那么您可以使用__in
Student.objects.filter(roll_no__in=[roll_no - 1, roll_no, roll_no + 1])
如果您无法保证他们总是增量,那么您可能需要先单独查询才能获得您想要首先找到的roll_no。
例如(没有错误/越界处理),
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]
答案 1 :(得分:0)
如果我理解正确,这就是你想要的
# 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)