SQLAlchemy事件如何在db session commit之后获取删除项信息

时间:2017-07-16 00:52:32

标签: python sqlalchemy flask-sqlalchemy

我正在使用非常好的SQLAlchemy事件,我可以使大量的重复工作无效。

现在我需要删除一些项目,并在删除操作后在after_delete侦听器中进行一些后期工作,但同时在after_delete侦听器中我需要使用那些已删除的项目信息,这是一段代码。

def shop_delete_category(category_id):
    item_category = ItemCategory.query.get(category_id)

    if item_category is None:
        result['code'] = 100
    else:
        deleted_category_id_items = ItemCategory.query.filter(ItemCategory.id == category_id).with_entities(ItemCategory.id).all()

        # some other business logic

        db.session.delete(item_category)
        db.session.commit()

我的事件监听器代码:

@event.listens_for(ItemCategory, 'after_delete')
def after_delete_shop_category(mapper, connect, target):
    # business logic 
    shop_category_delete_signal.send(target)

    # here will need deleted_category_id_items
    # how can I pass in ?
    # logic will be like this
    redis_cache_delete_category_ids(deleted_category_id_items)

我想在删除操作后执行一些后期工作,在删除操作中我会使用deleted_category_id_items,我的问题是

如何通过deleted_category_id_items事件传递?或者有更好的方法来解决这个问题吗?

编辑:我自己的答案

发现:before_delete监听器可以解决问题

编辑: 另一个问题我如何将自己的参数传递给侦听器,比如

@event.listens_for(ItemCategory, 'after_delete')
def after_delete_shop_category(mapper, connect, target, *my_own_paramters):
    # business logic 
    shop_category_delete_signal.send(target)

    # here will need deleted_category_id_items
    # how can I pass in ?
    # logic will be like this
    redis_cache_delete_category_ids(deleted_category_id_items)

    # can use my_own_paramters do some work

非常感谢!

0 个答案:

没有答案