Theron Luhn
Theron Luhn

Reputation: 4082

SQLAlchemy ORM before-insert hook

I'm trying to figure out how to write a hook to query the database before inserting a row from the ORM. I hope to achieve something similar to this:

class Table(Base):
    id = Column(Integer, primary_key=True)
    value = Column(Integer, nullable=False)

    def before_insert_hook(self, session):
        """Some arbitrary queries and code.  For example:"""
        if self.value is None:
            self.value = session.query(func.avg(Table.value))\
                    .filter(Table.value > 100).scalar()

I've been reading up in the SQLAlchemy docs about ORM events and such, but I can't figure out how to use them to achieve this.

Upvotes: 10

Views: 13341

Answers (1)

Ken Kinder
Ken Kinder

Reputation: 13140

Looks like you want ORM Events:

from sqlalchemy import event

class Table(Base):
    ...

@event.listens_for(Table, 'before_insert')
def do_stuff(mapper, connect, target):
    # target is an instance of Table
    target.value = ...

Upvotes: 17

Related Questions