在sqlalchemy中设置事件时区分插入和更新

时间:2014-06-25 10:24:51

标签: python sqlalchemy

如何区分插入或更新?

from sqlalchemy import event

@event.listens_for(SomeClass.some_attribute, 'set')
def receive_set(target, value, oldvalue, initiator):
    # Some logic..
    # Here i need to verify target is created or being updated.
    # Based on update/insert I have to set different value

1 个答案:

答案 0 :(得分:1)

请参阅object states上的文档。

持久状态是你所关心的。如果为false,则应进行插入,否则进行更新。

from sqlalchemy import event, inspect

@event.listens_for(SomeClass.some_attribute, 'set')
def receive_set(target, value, oldvalue, initiator):
    if inspect(target).persistent:
        # update here
    else:
        # create here