Skip to content

Instantly share code, notes, and snippets.

@krak3n
Created July 4, 2014 13:38
Show Gist options
  • Save krak3n/9fa1268ee0a92a67f71a to your computer and use it in GitHub Desktop.
Save krak3n/9fa1268ee0a92a67f71a to your computer and use it in GitHub Desktop.
Avoid DetachedInstanceError in Flask-SQLAlchemy
# The following produces DetachedInstanceError
app = Flask(__name__)
db = SQLAlchemy(app)
class Foo(db.Model):
id = db.Column(db.Integer, primary_key=True)
foo = Foo()
db.session.add(foo)
db.session.commit()
foo.id
>>> DetachedInstanceError: Instance <Foo at 0x10741ac10> is not bound to a Session; attribute refresh operation cannot proceed
# The following removes DetachedInstanceError
app = Flask(__name__)
db = SQLAlchemy(app, session_options{
'expire_on_commit': False
})
class Foo(db.Model):
id = db.Column(db.Integer, primary_key=True)
foo = Foo()
db.session.add(foo)
db.session.commit()
foo.id
>>> 1
@kalelsun
Copy link

kalelsun commented Aug 8, 2024

But you don't close the session, the commit operation just expire the orm object, why does this lead to produces DetachedInstanceError ?
flask-sqlalchemy auto close when commit ?

@krak3n
Copy link
Author

krak3n commented Aug 8, 2024

Gosh this is a blast from the past @kalelsun 😄 I no longer work with Python or Flash / SQL Alchemy so I can't really answer your question, sorry, of course this very old code at this point so I have no idea if it is still relevant.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment