Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy ORM before-insert hook

Tags:

orm

sqlalchemy

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.

like image 763
Theron Luhn Avatar asked Dec 12 '12 00:12

Theron Luhn


People also ask

Should I use SQLAlchemy core or ORM?

If you want to view your data in a more schema-centric view (as used in SQL), use Core. If you have data for which business objects are not needed, use Core. If you view your data as business objects, use ORM. If you are building a quick prototype, use ORM.

What does First () do in SQLAlchemy?

first() applies a limit of one within the generated SQL, so that only one primary entity row is generated on the server side (note this may consist of multiple result rows if join-loaded collections are present). Calling Query. first() results in an execution of the underlying query.

What is Sessionmaker in SQLAlchemy?

Session in SQLAlchemy ORM However, to standardize how sessions are configured and acquired, the sessionmaker class is normally used to create a top-level Session configuration which can then be used throughout an application without the need to repeat the configurational arguments.

Does commit close the Session SQLAlchemy?

commit() will then COMMIT the actual database transaction or transactions, if any, that are in place. Finally, all objects within the Session are expired as the transaction is closed out.


1 Answers

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 = ...
like image 186
Ken Kinder Avatar answered Oct 23 '22 13:10

Ken Kinder