SQLAlchemy出现'str'无'_sa_instance_state'属性错误如何处理
问题原因
你配置User和BlogPost的表关联后,BlogPost模型中的author是SQLAlchemy定义的关系字段,需要接收User类的实例对象,你在创建BlogPost时给author字段传入了current_user.name这个字符串值,SQLAlchemy处理关系字段时会查找实例的_sa_instance_state属性,字符串对象不存在该属性,因此触发报错。
此外你同时给author关系字段和author_id外键字段赋值属于冗余操作,二者选其一即可完成关联。
修复方案
方案1:给关系字段传正确的User实例
删除author_id赋值,将author字段的传值改为完整的current_user对象:
form = CreatePostForm() if form.validate_on_submit(): new_post = BlogPost( title=form.title.data, subtitle=form.subtitle.data, body=form.body.data, img_url=form.img_url.data, author=current_user, date=date.today().strftime("%B %d, %Y") ) db.session.add(new_post) db.session.commit() return redirect(url_for("get_all_posts")) return render_template("make-post.html", form=form)
方案2:仅传外键字段
不给author关系字段赋值,仅通过author_id外键完成关联:
form = CreatePostForm() if form.validate_on_submit(): new_post = BlogPost( title=form.title.data, subtitle=form.subtitle.data, body=form.body.data, img_url=form.img_url.data, author_id=current_user.id, date=date.today().strftime("%B %d, %Y") ) db.session.add(new_post) db.session.commit() return redirect(url_for("get_all_posts")) return render_template("make-post.html", form=form)
补充说明
关系字段是ORM层面的虚拟字段,不会实际存储在数据库表中,数据库仅会存储author_id这个外键字段,两种方案的最终存储效果完全一致,后续查询时都可以通过blog_post.author直接获取到对应的User实例。
内容的提问来源于stack exchange,提问作者giovanni sergi
相关产品推荐
相关产品推荐

