文章内容

2022/1/12 16:14:29,作 者: 黄兵

SQLAlchemy 多对多删除问题总结


最近在使用 SQLAlchemy 多对多模型需要删除,具体模型内容如下:

# 文章与标签之间多对多关系
blog_tag_associations = db.Table('ip_crawler_blog_tag_associations',
db.Column('blog_id', db.Integer, db.ForeignKey('ip_crawler_blog.id')),
db.Column('tag_id', db.Integer, db.ForeignKey('ip_crawler_blog_tags.id')),
info={'bind_key': 'ip_crawler_db'})

这是一个中间表,如果我们需要删除,非常麻烦,我们可以使用 ondelete 来级联删除,具体示例代码如下:

# 文章与标签之间多对多关系
blog_tag_associations = db.Table('ip_crawler_blog_tag_associations',
db.Column('blog_id', db.Integer,
db.ForeignKey('ip_crawler_blog.id', ondelete='CASCADE')),
db.Column('tag_id', db.Integer, db.ForeignKey('ip_crawler_blog_tags.id',
ondelete='CASCADE')),
info={'bind_key': 'ip_crawler_db'})

上面代码设置的是级联删除,同时我们可以这样设置:

# 文章与标签之间多对多关系
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'})

可用的级联 save-updatemergeexpungedeletedelete-orphanrefresh-expire


上面是文章表和标签表的删除数据操作,如果是反射表(辅助表:ip_crawler_blog_tag_associations)可以参考这篇文章:SQLAlchemy 辅助表删除记录


参考资料:

1、SQLAlchemy 1.4 Documentation - Cascades

2、sqlalchemy中多对多关系级联删除的问题

分享到:

发表评论

评论列表