Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How set event on field in SQLAlchemy, that it will call only when changes concern db

I am using SQLAlchemy, and face a problem, that I need to handle event, when one field in table is changed. Firstly, I've tried to use code from docs:

@listen_for(Advert.status, 'set')
def handle_change_status(target, value, oldvalue, initiator):
    if value != oldvalue:
         # do smth

But this event occure any time the field is changed, even if we do not modify db. For example:

advert=Advert()
advert.status = 3  # event apear

But I need that event appear only when I commit changes:

db.session.add(advert)
db.session.commit()  # I need event occure here

I think that I can handle each 'set' event and write them in some storage, and then add event on session.commit (after_commit) and in this event handle all set events. But this approach seems not to be very neat.

May be someone has any ideas, how to solve this problem?

like image 725
Igor Avatar asked Sep 20 '25 15:09

Igor


1 Answers

So, I have solve this question that way:

Firstly, I've created init where save init value: def __init__(self): self._init_value = self.value

Also I've declared method, that do the same, when orm reconstruct object from db:

@orm.reconstructor def init_on_load(self): self.__init__()

And then I created events:

@event.listens_for(Model, 'after_update')
def compare_old_and_new_values(mapper, connection, target):
    if target._init_value != target.value:
        # do smth

@event.listens_for(Model, 'after_insert')
def compare_old_and_new_values(mapper, connection, target):
    if target._init_value != target.value:
        # do smth

`

I think this approach can have some misbehaviour, when multiple users change the same record in db, but this aproach save us from making additionals SQL queries to db.

like image 194
Igor Avatar answered Sep 22 '25 04:09

Igor