Created
July 4, 2014 13:38
-
-
Save krak3n/9fa1268ee0a92a67f71a to your computer and use it in GitHub Desktop.
Avoid DetachedInstanceError in Flask-SQLAlchemy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you very much help. This helped to solve my problem.