Skip to content

Instantly share code, notes, and snippets.

@krak3n
Created July 4, 2014 13:38
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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
@askaliuk
Copy link

Thank you for sharing. How do you run Flask? Uwsgi? Multi-thread? Multi-process?

@bwangelme
Copy link

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

# The following produces DetachedInstanceError

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)
# db = SQLAlchemy(app, session_options={
#     'expire_on_commit': False
# })

class Foo(db.Model):
    id = db.Column(db.Integer, primary_key=True)

db.create_all()
foo = Foo()
db.session.add(foo)
db.session.commit()
print(foo.id)

I have ran the above code on my computer, but it didn't raise a DetachedInstanceError,the flask version on my computer is:

Flask==0.12
Flask-SQLAlchemy==2.2
SQLAlchemy==1.1.6

@daassh
Copy link

daassh commented Mar 25, 2021

I have troubleshooting this issue half day, this is realy help me.
thank you very much!

@yeboah326
Copy link

Thank you very much help. This helped to solve my problem.

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