如何区分插入或更新?
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
答案 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