想从数据库中将特定条件的数据项传递到模板中,出现了模板中该参数值为空的问题
# 传递参数之前,使用过此查询语句,是将查询结果存入变量current_prescription中
current_prescription = Prescription.query.filter_by(inquiry_info=info.id).first()
#在模板渲染语句中,同样使用该查询语句,将查询结果传递到模板文件中
return render_template('output.html', Pre=Prescription.query.filter_by(inquiry_info=info.id).first())
无报错,但是模板中该参数为空
将此语句
return render_template('output.html', Pre=Prescription.query.filter_by(inquiry_info=info.id).first())
修改为
return render_template('output.html', Pre=current_prescription)
即直接将存入过的current_prescription传到模板文件中,发现成功传递
为什么再次使用此查询语句传递参数会导致传递为空,而使用存好的变量,就不会出现此问题呢?
# 传递参数之前,使用过此查询语句,是将查询结果存入变量current_prescription中
current_prescription = Prescription.query.filter_by(inquiry_info=info.id).first()
#在模板渲染语句中,同样使用该查询语句,将查询结果传递到模板文件中
return render_template('output.html', Pre=Prescription.query.filter_by(inquiry_info=info.id).first())
这2句是同时在代码里面?
如果是,可能是查询的库filter_by在同一个会话中只能使用一次,导致给current_prescription 赋值后记录集中已经没记录了,所以render_template再调用返回空值之类的,题主看下读取数据库模块的逻辑,first()能正常返回值不用单独赋值给变量的
或者试试下面的,再次调用first()看能否打印出数据
# 传递参数之前,使用过此查询语句,是将查询结果存入变量current_prescription中
current_prescription = Prescription.query.filter_by(inquiry_info=info.id).first()
print(Prescription.query.filter_by(inquiry_info=info.id).first())#######再次调用first()看能否打印出数据,不能说明查询类库和我猜测的一样
#在模板渲染语句中,同样使用该查询语句,将查询结果传递到模板文件中
return render_template('output.html', Pre=Prescription.query.filter_by(inquiry_info=info.id).first())