我看過很多關于更新 SQLAlchemy 資料的帖子,但我無法準確找到我一直在尋找的東西,即使存在。我正在使用燒瓶、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,
)
因為我不知道用戶想要更新表單中的哪些欄位,所以我想要一種簡單的方法來更新整個記錄,而我現在必須單獨更新每個欄位。任何幫助或建議將不勝感激。
uj5u.com熱心網友回復:
您可能想看看 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())
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/491913.html
