After_insert event on another table

I have table A and table B where I would like to add / update / delete columns in table B in table A events. I tried the following:

  • Mapper events aka @ event.listens_for (SomeClass, 'before_insert')

The documentation states

Cardboard level flash events are designed to work with attributes local to the immediate object being processed and through SQL operations on a given connection ... Operations that are not supported in mapping events include: Session.add () Session. delete () ... Set mapping attribute / del events

This limits everything I can do with other tables. For example,

def after_insert_listener(mapper, connection, target):
    target.value = "New Value"

      

works fine and

def after_insert_listener(mapper, connection, target):
    target.child.count += 1

      

doesn't do the trick. Typing db.session.commit () gives me this error

ResourceClosedError: This transaction is closed

I tried using SessionEvents.before_flush (), but none of them could be tied to a specific model and I didn't figure out how to use it.

  1. Flask-SQLAlchemy Signals

I've tried using signal_committed signal:

@models_committed.connect_via(app)
def on_models_committed(sender, changes):
    for obj, change in changes:
        if change == 'delete' and hasattr(obj, '__after_delete__'):
            obj.__after_delete__()
        elif change == 'update' and hasattr(obj, '__after_update__'):
            obj.__after_update__()
        elif change == 'insert' and hasattr(obj, '__after_insert__'):
            obj.__after_insert__()

class TableA(db.Model):
    def __after_insert__(self):
        self.child.count += 1
        self.value = "New Value"
        db.session.commit()

      

It gave me

InvalidRequestError: This session is in "commit" state; no other SQL can be dropped in this transaction.

How do I update instances of a model after installing another model?

+3


source to share


1 answer


You may try,



        @event.listens_for(B, "after_insert")
        def after_insert_listener(mapper, connection, target):
            A_table = A.__table__
            connection.execute(
                    A_table.update().
                     where(A_table.id==target.a_table.id). # Do Foreign key join porperly 
                     values(value='New Value')
            )

      

+1


source







All Articles