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

请教如何在 sqlalchemy model 的 event 里面停止删除或者用其他方式实现软删除

  •  
  •   efrigate43 · 2022-02-15 02:39:37 +08:00 · 2004 次点击
    这是一个创建于 808 天前的主题,其中的信息可能已经有所发展或是发生改变。

    如题

    model

    
    def crudset(classModel):
    from datetime import datetime as dt
    
        @event.listens_for(classModel, "before_insert")
        def model_brfore_insert(target, value, initiator):
            initiator.dt_create = dt.now().strftime("%Y-%m-%d %H:%M:%S")
    
        @event.listens_for(classModel, "before_update")
        def model_brfore_update(target, value, initiator):
            initiator.dt_update = dt.now().strftime("%Y-%m-%d %H:%M:%S")
    
        @event.listens_for(classModel, "before_delete")
        def model_before_delete(target, value, initiator):
            from copy import deepcopy
    
            item = deepcopy(initiator)
            item.dt_delete = dt.now().strftime("%Y-%m-%d %H:%M:%S")
    
            print(str(item))
        
    

    正在写 model_before_delete 这个方法,如何能把 dt_delete 这个字段的值 作为软删除的标志,并且停止当前删除的操作,已达到软删的目的,又或者有什么软删的附加库可用吗?

    我初学者刚接触不久 请各位大佬赐教

    3 条回复    2022-02-15 10:50:59 +08:00
    Latin
        1
    Latin  
       2022-02-15 09:48:28 +08:00
    手动实现 软删除标识字段赋值
    lolizeppelin
        3
    lolizeppelin  
       2022-02-15 10:50:59 +08:00
    如果你的删除是 object.delete()的方式 重写 delete 方式就好把?

    全局的话在监听事件里似乎不能直接做到啊,sqlalchemy 代码太复杂了建议不要这么搞....
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2245 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 08:55 · PVG 16:55 · LAX 01:55 · JFK 04:55
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.