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
fanhaipeng0403
V2EX  ›  Python

Sqlalchemy 的级联删除配置

  •  
  •   fanhaipeng0403 · 2018-11-12 16:36:30 +08:00 · 1771 次点击
    这是一个创建于 2208 天前的主题,其中的信息可能已经有所发展或是发生改变。
    
    class BaseModel(Model):
        id = Column(Integer, primary_key=True)
        created_at = Column(DateTime(True), default=func.now(), nullable=False)
        updated_at = Column(DateTime(True), default=func.now(), onupdate=func.now(), nullable=False)
    
        @classmethod
        def create(cls, **kw):
            session = db.session
            if 'id' in kw:
                obj = session.query(cls).get(kw['id'])
                if obj:
                    return obj
            obj = cls(**kw)
            session.add(obj)
            session.commit()
            return obj
    
        def to_dict(self):
            columns = self.__table__.columns.keys()
            return {key: getattr(self, key) for key in columns}
    
    
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///../cnblogblog.db'
    
    db = SQLAlchemy(app, model_class=BaseModel)
    
    
    ######################################################################################################
    
    class Parent(db.Model):
        __tablename__ = 'parent'
        id = Column(Integer, primary_key=True)
        name = Column(String(20))
    
    
    class Child(db.Model):
        __tablename__ = 'child'
        id = Column(Integer, primary_key=True)
        name = Column(String(20))
    
        parent_id = Column(Integer, ForeignKey('parent.id'))
        parent = relationship("Parent", backref=backref("child"))
    
        ###  只删除父级,子不影响
        # 1. parent_id = Column(Integer, ForeignKey('parent.id', ondelete="CASCADE"))
        #    parent = relationship("Parent", backref=backref("child", passive_deletes=True))
    
        ###  子级跟随删除
        # 2. parent = relationship("Parent", backref = backref("child", cascade="all, delete-orphan"))
        # 3. parent = relationship("Parent", backref = backref("child", cascade="all,delete"))
    
        ##  父级删除,子级不删除,外键更新为 null
        # 4. parent = relationship("Parent", backref = backref("child"))
    
    
    if __name__ == '__main__':
        db.create_all()
        Parent.create(name='ZhangTian')
        Parent.create(name='LiTian')
        Child.create(name='ZhangDi', parent_id=1)
        Child.create(name='LiDi', parent_id=2)
    
        parent = db.session.query(Parent).first()
        db.session.delete(parent)
        db.session.commit()
        ```
    
    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1742 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 21ms · UTC 16:40 · PVG 00:40 · LAX 08:40 · JFK 11:40
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.