V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
Tianny
V2EX  ›  Python

问个 flask SQLAlchemy 多对多关系的级联删除问题。求解答、

  •  
  •   Tianny · 2017-12-15 20:40:50 +08:00 · 3472 次点击
    这是一个创建于 2323 天前的主题,其中的信息可能已经有所发展或是发生改变。

    一个 post 表,代表博客文章,一个 tag 表,代表文章的分类标签,这两个多对多关系,关联表叫 post_tags。

    我想删除一个 id=103 的 post,同时级联删除关联表中的记录。应该怎么操作呢?搜了一圈,需要加上cascade="all, delete-orphan",这些参数,但是好像这些都只适用于一对多的,多对多的应该怎么解决呢?请教下大家 谢谢!

    post=Post.query.filter_by(id=103).first()
    db.session.delete(post)
    db.session.commit()
    

    下面是基本的 Model

    class Post(db.Model):
        id = db.Column(db.Integer(), primary_key=True)
        tags = db.relationship('Tag', secondary=tags, backref=db.backref('posts', lazy='dynamic'))
    
    class Tag(db.Model):
        id = db.Column(db.Integer(), primary_key=True)
        title = db.Column(db.String(255))
    
    tags = db.Table('post_tags', db.Column('post_id', db.Integer, db.ForeignKey('post.id')),
                    db.Column('tag_id', db.Integer, db.ForeignKey('tag.id')))
    
    7 条回复    2017-12-16 13:43:05 +08:00
    Tianny
        1
    Tianny  
    OP
       2017-12-15 20:46:48 +08:00
    给个思路也可以!感谢大家!
    BBCCBB
        2
    BBCCBB  
       2017-12-15 21:18:09 +08:00
    不会 sqlalchemy, 帮顶
    Tianny
        3
    Tianny  
    OP
       2017-12-15 21:38:53 +08:00
    @BBCCBB 其实我表述的不对。post 和 tag 是多对多关系,post 和 comment 是一对多的关系。需求是这样的,我要删除某个 post,及该 post 对应的 comment。但是好像因为外键的关系,我无法直接删除 post。请问应该怎么解决呢?
    testcount
        4
    testcount  
       2017-12-15 22:19:33 +08:00 via Android
    不加外键(实际也很少用),直接用 post_id 查标记删除就是了。
    cevincheung
        5
    cevincheung  
       2017-12-15 22:22:59 +08:00
    删 post 和对应的 comment 但是不删 tags ?但是因为 post 和 tags 同时有外键约束所以还不能删 post ?
    shn7798
        6
    shn7798  
       2017-12-16 12:57:48 +08:00
    多对多只能删除关联, 不能删除子表记录,不然把 tags 删了你叫别的 post 怎么找到他的 tags?
    Tianny
        7
    Tianny  
    OP
       2017-12-16 13:43:05 +08:00 via iPhone
    @shn7798 是的!谢啦😁
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1467 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 23:56 · PVG 07:56 · LAX 16:56 · JFK 19:56
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.