Python SQLAlchemy sets event binding

In SQLAlchemy ORM, you can bind an attribute set event for all tables and columns using this code:

@event.listens_for(Base, 'attribute_instrument')
def configure_listener(class_, key, inst):    
    if not hasattr(inst.property, 'columns'):
        return

    @event.listens_for(inst, "set", retval=True)
    def set_column_value(instance, value, oldvalue, initiator):
        column = inst.property.columns[0]
        # HOOK CODE
        logging.info("%s: %s -> %s" % (inst.property.columns[0], oldvalue, value))
        return value 

But this approach is not suitable for relationships. Attributes of the table, which are relations, do not go through this event, and the official leadership says nothing that the attributes of relations will not be processed by the event. So the question is: is there any way in SQLAlchemy to associate events with a change in a relation attribute?

Note: I was hoping that the relations associated with another table using a foreign key column, then changing this (foreign key) would generate an event, but I was wrong: this is true only when the record already has a valid identifier, but otherwise ( when the object has not yet been added to the database) this event has not been created.

+4
source share
1 answer

I think there is now an event init_collectionin 1.0 sqlalchemy

http://docs.sqlalchemy.org/en/latest/orm/events.html#attribute-events

0
source

Source: https://habr.com/ru/post/1539462/


All Articles