SQLAlchemy 不更新记录

SQLAlchemy not updating record

我没有收到任何错误,只是没有更新记录。我正在编辑用户记录并保存单个字段(我不能使用 populate_obj() 因为我只更新了 select 几个字段但是在 db.session.commit() 之后它仍然没有更新 table.

@app.route("/user/edit/<int:user_id>", methods=["GET", "POST"])
@login_required
def edit_user(user_id):
    user = User.query.get_or_404(user_id)
    form = EditUserForm()
    form.username.data = user.username
    form.email.data = user.email
    form.first_name.data = user.first_name
    form.last_name.data = user.last_name
    if form.validate_on_submit():
        user.email = form.email.data
        user.first_name = form.first_name.data
        user.last_name = form.last_name.data
        db.session.commit()
        flash("Updated user '{}'".format(user.username))
        return redirect(url_for("user"))
    return render_template("user_edit_form.html", form=form, action="Edit", user_id=user_id)

它甚至重定向闪现它更新记录的消息,但 sqlachemy 没有向 mysql 数据库写入任何内容。

commit() 之后添加 db.session.flush() 没有任何区别,在提交之前将用户添加到会话中也没有区别 (db.session.add(user))。

如何更新记录?

请记住,提交表单时仍会执行 if form.validate_on_submit 之前的代码——在该代码中,您将使用数据库中的数据覆盖表单数据。

假设用户在提交的表单上将他们的电子邮件从 'old@foo.com' 更改为 'new@foo.com'——如果我们在表单是有效分支时将执行以下代码:

user = User.query.get_or_404(user_id)
form = EditUserForm()
form.username.data = user.username
# at this point form.email.data would be 'new@foo.com' but....
form.email.data = user.email # we then override it with 'old@foo.com'
form.first_name.data = user.first_name
form.last_name.data = user.last_name
user.email = form.email.data # read 'old@foo.com' from the data (since we over-rode it above)
user.first_name = form.first_name.data
user.last_name = form.last_name.data
db.session.commit().
flash("Updated user '{}'".format(user.username))
return redirect(url_for("user"))

所以 new@foo.com 数据甚至在验证表单之前就被销毁了。所以当你更新时,你只是更新了已经存储的值。