文章内容
2023/11/7 16:50:31,作 者: 黄兵
AttributeError: 'dict' object has no attribute '_sa_instance_state'
在使用 SQLAlchemy 更新数据的时候,出现了如下错误:
AttributeError: 'dict' object has no attribute '_sa_instance_state'
主要代码如下:
get_tags = get_blog.tags.all()
for tag in get_tags:
# 标签,先删除再增加
get_tag = AmericaShopBlogTag.query.filter_by(id=tag.id).first()
get_blog.tags.remove(get_tag)
get_blog.tags = get_tags_list这是一个大家很常见的博客文章代码,博客文章有标签,标签与文章之间肯定是多对多的关系,所以我们再更新标签的时候,首先需要查询出该文章的所有标签🏷,之后删除,删除完成之后增加。
其中 get_tags_list 是一个字典个的数据类型,具体数据如下:
[{'id': 2, 'name': 'Feature'}]出现上面的问题可能模型与字段对不上,我们需要循环取出里面的 id 值,之后通过 id 查询 Tag 表,修改代码如下:
get_tags = get_blog.tags.all()
for tag in get_tags:
# 标签,先删除再增加
get_tag = BlogTag.query.filter_by(id=tag.id).first()
get_blog.tags.remove(get_tag)
for item in get_tags_list:
tag = BlogTag.query.get(item['id'])
get_blog.tags.append(tag)
get_categories = get_blog.categories.all()
for category in get_categories:
# 目录,先删除再增加
get_category = BlogCategory.query.filter_by(category.id).first()
get_blog.categories.remove(get_category)
for item in get_category_list:
category_item = BlogCategory.query.get(item['id'])
get_blog.categories.append(category_item)
db.session.add(get_blog)最后问题解决。上面这个错误,网上也没有找到很好的解释。
其它相关推荐:
1、time data '2023-07-28T08:57:48.238Z' does not match format '%Y-%m-%dT%H:%M:%SZ'
2、TypeError: Rule.__init__() got an unexpected keyword argument 'method'
3、AttributeError: 'AnonymousUser' object has no attribute 'id'
4、TypeError: unsupported operand type(s) for *: 'decimal.Decimal' and 'float'
5、AttributeError: 'function' object has no attribute 'route'
黄兵个人博客原创。
转载请注明出处:黄兵个人博客 - AttributeError: 'dict' object has no attribute '_sa_instance_state'
评论列表