由于我有很多列,所以我试图自动更新数据库。 我已经成功使用for循环显示数据库,但是在将更改提交到数据库时遇到了问题:
@app.route('/listvehicle/<int:vehicle_id>/update', methods=['GET', 'POST'])
@login_required
def update_vehicle(vehicle_id):
vehicle = Vehicle.query.get_or_404(vehicle_id)
form = VehicleUpdateForm()
if form.validate_on_submit():
for attr,value in vehicle.__dict__.items():
for ia in form:
if ia == attr:
vehicle.__dict__[attr] = form.__dict__[ia]
db.session.commit()
flash(f'The user has been updated', 'success')
return redirect(url_for('listvehicle'))
elif request.method == 'GET':
for attr,value in vehicle.__dict__.items():
for ia,iv in form.__dict__.items():
if ia == attr:
iv.data = value
return render_template('updatevehicle.html', form=form)
对将更改提交到数据库有帮助吗?
答案 0 :(得分:1)
我建议您发布“模型”和“表单”定义,但不建议您使用其他方法,强烈建议您不要更改带有双下划线的任何内容(例如,__dict__
)。
我看到可以简单地通过使用setattr
并遍历表单数据来进行改进:
def update_vehicle(vehicle_id):
vehicle = Vehicle.query.get_or_404(vehicle_id)
form = VehicleUpdateForm()
if form.validate_on_submit():
for fieldname, value in form.data.items():
setattr(vehicle, fieldname, value)
db.session.commit()
flash(f'The user has been updated', 'success')
return redirect(url_for('listvehicle'))
elif request.method == 'GET':
for attr,value in vehicle.__dict__.items():
for ia,iv in form.__dict__.items():
if ia == attr:
iv.data = value
return render_template('updatevehicle.html', form=form)