Why does a query invoke a auto-flush in SQLAlchemy? Why does a query invoke a auto-flush in SQLAlchemy? python-3.x python-3.x

Why does a query invoke a auto-flush in SQLAlchemy?


How to turn off autoflush feature:

  • Temporary: you can use no_autoflush context manager on snippet where you query the database, i.e. in X.test method:

    def test(self, session):    with session.no_autoflush:        q = session.query(X).filter(X._val == self._val)        x = q.one()        print('x={}'.format(x))
  • Session-wide: just pass autoflush=False to your sessionmaker:

    return sao.sessionmaker(bind=engine, autoflush=False)()


I know this is old but it might be helpful for some others who are getting this error while using flask-sqlalchemy. The below code has fixed my issue with autoflush.

db = SQLAlchemy(session_options={"autoflush": False})