编辑具有唯一字段的对象:unique约束失败:blog_post.title



我正在尝试更新具有唯一的标题字段的记录。当我编辑标题以外的任何其他字段时,我得到这个错误:唯一约束失败:blog_post.title,但当我编辑标题时,会创建一个新对象。我已经查找了示例和周围的工作,无法找到解决它的合适方法。

那么我如何更新记录而不出现此错误?

My database
class BlogPost(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(250), unique=True, nullable=False)
subtitle = db.Column(db.String(250), nullable=False)
date = db.Column(db.String(250), nullable=False)
body = db.Column(db.Text, nullable=False)
author = db.Column(db.String(250), nullable=False)
img_url = db.Column(db.String(250), nullable=False)
my ulr path
@app.route("/edit-post/<int:post_id>", methods=['GET','POST'])
def edit_post(post_id):
post_edit = BlogPost.query.get_or_404(post_id)
edit_form = CreatePostForm(request.form, obj=post_edit)
if edit_form.validate_on_submit():
edit_form.populate_obj(post_edit)
db.session.commit()
return redirect(url_for("show_post", index=post_edit.id))
return render_template("make-post.html", form=edit_form, is_edit=True)

我认为,因为你正在创建一个新的实例,而不是实际更新一个现有的记录,获取你的记录后,通过它的id开始改变所需的字段值,然后调用保存方法。

post_edit.body="Example"
post_edit.save()

最新更新