Clone wiki

sqlalchemy / UsageRecipes / DisableAutoflush

Disable Autoflush

"autoflush" on a Session can be controlled at any time by setting the value of the autoflush attribute. Here we illustrate common patterns for implementing blocks of code with autoflush temporarily disabled.

Note: This feature is now included as of SQLAlchemy 0.7.6:

# 0.7.6 and above
with session.no_autoflush:
    myobject.foobar.add(someobj)

Method one - the with method:

class no_autoflush(object):
    def __init__(self, session):
        self.session = session
        self.autoflush = session.autoflush

    def __enter__(self):
        self.session.autoflush = False

    def __exit__(self, type, value, traceback):
        self.session.autoflush = self.autoflush

usage:

with no_autoflush(mysession):
    myobject.foobar.add(someobj)

Method two: decorator

from functools import update_wrapper

def no_autoflush(scoped_session):
    def decorate(fn):
        def go(*args, **kw):
            session = scoped_session()
            autoflush = session.autoflush
            session.autoflush = False
            try:
                return fn(*args, **kw)
            finally:
                session.autoflush = autoflush

        return update_wrapper(go, fn)
    return decorate

This method is more appropriate with a ScopedSession since the decorator is typically declared at the class level. Usage:

Session = scoped_session(sessionmaker())

@no_autoflush(Session)
def do_something():
    Session.add(someobj)
    someobj.collection.add(someotherobj)

Updated