SQLAlchemy删除文章时多对多删除,文章标签不删除标签吗?

时间:2019-09-20 01:30:18

标签: sqlalchemy flask-sqlalchemy

  1. 如何删除帖子并自动删除其相关的post_tags记录。但是,不要删除标签吗?

  2. 应如何配置?

  3. 模型代码

post_tags = db.Table('post_tags',
                       db.Column('post_id', db.Integer, db.ForeignKey('posts.id',ondelete='CASCADE'),
                                 primary_key=True),
                       db.Column('tag_id', db.Integer, db.ForeignKey('tags.id',ondelete='CASCADE'), primary_key=True)
                       )

class Posts(db.Model):
    __tablename__ = "posts"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(40))
    tags = db.relationship("Tags", secondary=post_tags, backref=db.backref("posts", lazy="dynamic"),
                                  lazy="dynamic",cascade="all, delete-orphan",single_parent=True)  #,passive_deletes=True
class Tags(db.Model):
    __tablename__ = "tags"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(40))

post = Posts.query.get(1)
db.session.delete(post) # how to auto delete `post_tags`record,but dont delete `tags`record. 
db.session.commit()
  1. 运行
post = Posts.query.get(1)
db.session.delete(post) # how to auto delete `post_tags`record,but dont delete `tags`record. 
db.session.commit()

当我执行代码时,此帖子,post_tags和标签,全部删除。 我只想删除post和post_tags。 我应该如何配置?

=======================================

我什么都不添加,这很理想。

tags = db.relationship("Tags", secondary=post_tags,backref=db.backref("posts", lazy="dynamic"),lazy="dynamic")

0 个答案:

没有答案