文章内容
2022/1/13 19:13:40,作 者: 黄兵
SQLAlchemy 辅助表删除记录
有几个模型的代码如下:
# 文章相关表 class IPCrawlerBlog(db.Model): __tablename__ = 'ip_crawler_blog' id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(64)) body = db.Column(db.Text) # 文章与标签之间多对多关系 blog_tag_associations = db.Table('ip_crawler_blog_tag_associations', db.Column('blog_id', db.Integer, db.ForeignKey('ip_crawler_blog.id', ondelete='all, delete-orphan')), db.Column('tag_id', db.Integer, db.ForeignKey('ip_crawler_blog_tags.id', ondelete='all, delete-orphan')), info={'bind_key': 'ip_crawler_db'}) # 文章标签 class IPCrawlerBlogTag(db.Model): __tablename__ = 'ip_crawler_blog_tags' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), unique=True) link_text = db.Column(db.String(32), unique=True, index=True) blogs = db.relationship('IPCrawlerBlog', secondary=blog_tag_associations, backref=db.backref('ip_crawler_blog_tags', lazy='dynamic'), lazy='dynamic')
如果需要多表经行插入数据可以参考这篇文章:SQLAlchemy 多对多插入数据
我们需要对反射表(辅助表)数据进行删除,具体代码如下:
# 移除博客的所有标签 get_blog_all_tags = get_blog_by_id.ip_crawler_blog_tags.all() if get_blog_all_tags: # 存在标签,获取每个标签 for item in get_blog_all_tags: # 移除标签 get_blog_by_id.ip_crawler_blog_tags.remove(item)
首先查询出当前博客的所有标签:
get_blog_all_tags = get_blog_by_id.ip_crawler_blog_tags.all()
之后对每个标签经行循环遍历,依次删除:
for item in get_blog_all_tags: # 移除标签 get_blog_by_id.ip_crawler_blog_tags.remove(item)
这样就完成了反射表(辅助表)的数据删除。
同时我们也可以用这种方式删除:
post = db.session.query(Post).get(1) post.tags = [] db.session.commit()
如果需要删除博客文章或者是某个标签,由于模型设置了级联删除,同时使用 ondelete='all, delete-orphan'
启用所有默认层叠选项,同时还会删除孤儿记录。
这样只要删除博客或者标签,默认反射表(辅助表)的数据也会被删除。
参考资料:
1、How to delete records from many-to-many (secondary) table in SQLAlchemy?
2、《Flask Web 开发:基于 Python 的 Web 应用程序开发实战》[美] Miguel Grinberg 著
黄兵个人博客原创。
转载请注明出处:黄兵个人博客 - SQLAlchemy 辅助表删除记录
评论列表