从表单数据更新SQLAlchemy对象的简单方法



我已经看到了很多关于更新SQLAlchemy数据的帖子,但是我还没能找到我一直在寻找的东西,如果存在的话。我正在使用flask, SQLAlchemy和wtforms创建一个博客网站,并有一个页面允许用户使用表单更新他们的博客文章。博客文章存储在数据库中,当用户点击"提交"时。在编辑页面上,应该使用任何更改更新SQLAlchemy ORM对象。以下是我的edit_post路由的代码:

@app.route("/edit/<int:post_id>", methods=["GET", "POST"])
def edit_post(post_id):
post_to_edit = BlogPost.query.get(post_id)
edit_form = CreatePostForm(
title=post_to_edit.title,
subtitle=post_to_edit.subtitle,
img_url=post_to_edit.img_url,
author=post_to_edit.author,
body=post_to_edit.body
)
if edit_form.validate_on_submit():
post_to_edit.title = edit_form.title.data
post_to_edit.subtitle = edit_form.subtitle.data
post_to_edit.img_url = edit_form.img_url.data
post_to_edit.author = edit_form.author.data
post_to_edit.body = edit_form.body.data    
db.session.commit()
return redirect(url_for("show_post", index=post_id))
return render_template("make-post.html", form=edit_form)

这段代码可以工作,但我想我是在试着弄清楚我是否可以使它更简洁或更优雅。我知道SQLAlchemy有一个update()方法,我尝试了以下方法,但它不起作用。

post_to_edit.update(
{
BlogPost.title: edit_form.title.data,
BlogPost.subtitle: edit_form.subtitle.data,
BlogPost.date: post_to_edit.date,
BlogPost.body: edit_form.body.data,
BlogPost.author: edit_form.author.data,
BlogPost.img_url: edit_form.img_url.data,
},
synchronize_session=False,
)

因为我不知道用户想要更新的表单中的哪些字段,我想要一种简单的方法来更新整个记录,必须单独更新每个字段,因为我现在已经得到了它。如有任何帮助或建议,我将不胜感激。

您可能想看看flask-wtf的populate_obj函数。此外,给定的示例向您展示了如何通过使用obj参数将所请求的数据库对象传递给表单来填充表单。

@app.route('/edit/<int:post_id>', methods=['GET', 'POST'])
def edit_post(post_id):
post = BlogPost.query.get_or_404(post_id)
form = CreatePostForm(request.form, obj=post)
if form.validate_on_submit():
form.populate_obj(post)
db.session.commit()
return redirect(url_for('show_post', index=post_id))
return render_template('make-post.html', **locals())

最新更新