Skip to content Skip to sidebar Skip to footer

Sqlalchemy Object Already Attached To Session

I'm trying to get a server for an app working, but I'm getting an error upon login: [!] Object '' is already attached to session '2' (this is '3') It

Solution 1:

Object you're trying to modify is already attached to another session. Maybe you have wrong imports, and db_session is a new instance.

A good workaround to this is to extract the current bound session and use it:

Instead of:

db_session.add(s)

Do:

current_db_sessions = db_session.object_session(s)
current_db_sessions.add(s)

Solution 2:

As @marcinkuzminski mentioned, you can't add an object that is already attached to another session. Just pulling in the original session from the object with object_session() is risky, though, if you aren't sure that session originated in the same thread context you're currently operating in. A thread-safe method is to use merge():

    local_object = db_session.merge(original_object)
    db_session.add(local_object)
    db_session.commit()

Solution 3:

This db session issue will arise if you are having server.py and model.py importing each other

server.py

from flask import Flask
import os
import models as appmod #################### importing models here in server.py<----------

app = Flask(__name__)                                  # L1
app.config.from_object(os.environ['APP_SETTINGS'])     # L2
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False# L3
database = SQLAlchemy(app)                             # L4
db = database                                          # L5@app.route('/item_delete/<id>', methods=['DELETE'])defremove_method(id = None):
    data_rec = appmod.Employee.query.get(id)    
    db.session.delete(data_rec)
    db.session.commit()
    return"DELETE"if __name__ == '__main__':

    app.run(port=5000, host='0.0.0.0',debug=True,threaded=True)

models.py

from server import db #################### importing server in models.py here <------------from sqlalchemy.dialects.mysql import JSON


classEmployee(db.Model):
    __tablename__ = 'employe_flask'id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(128))
    datetime = db.Column(db.DateTime)
    designation = db.Column(db.String(128))


    def__init__(self, name, datetime, designation):
        self.name = name
        self.datetime = datetime
        self.designation = designation

    @staticmethoddefdelete_rec(data_rec):
        db.session.delete(data_rec)#.delete
        db.session.commit()

    def__repr__(self):
        record = {"name":self.name,"date":self.datetime.ctime(),"designation":self.designation}.__str__()
        return record

Remove the line L1 to L5 from server.py and place it in common file like settings.py and import 'app' and 'db' to server.py and import db in models.py

like this files below

server.py

from flask import Flask
import os
import models as appmod 
from settings import app, db


@app.route('/item_delete/<id>', methods=['DELETE'])defremove_method(id = None):
    data_rec = appmod.Employee.query.get(id)    
    db.session.delete(data_rec)
    db.session.commit()
    return"DELETE"if __name__ == '__main__':

    app.run(port=5000, host='0.0.0.0',debug=True,threaded=True)

settings.py

import os
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)                                  # L1
app.config.from_object(os.environ['APP_SETTINGS'])     # L2
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False# L3
database = SQLAlchemy(app)                             # L4
db = database                                          # L5

models.py

from settings import db
from sqlalchemy.dialects.mysql import JSON


classEmployee(db.Model):
    __tablename__ = 'employe_flask'id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(128))
    datetime = db.Column(db.DateTime)
    designation = db.Column(db.String(128))


    def__init__(self, name, datetime, designation):
        self.name = name
        self.datetime = datetime
        self.designation = designation

    @staticmethoddefdelete_rec(data_rec):
        db.session.delete(data_rec)#.delete
        db.session.commit()

    def__repr__(self):
        record = {"name":self.name,"date":self.datetime.ctime(),"designation":self.designation}.__str__()
        return record

Solution 4:

This error means the record you are handling is attached to 2 different session(db)!

One of the reasons is that you may define your model with one db = SQLAlchemy(app) and add/insert/modify the database with another!

My solution is UNIFORMING THE DB!

try this:

u = db.session.query(User).filter(User.username == request.form["username"]).first()

Instead of this:

u = User.query.filter(User.username == request.form["username"]).first()

Solution 5:

I had this problem too. I created a test_file.py and added this code:

from app import app
from models import Tovar  
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)

tovardel = Tovar.query.filter(Tovar.region == 1and Tovar.price == 12).first()
db.session.delete(tovardel)
tovar = Tovar.query.filter(Tovar.region == 1and Tovar.price == 12).first()
print(tovar.description)

and when I ran the code I got this error:

Object '<Tovar at 0x7f09cbf74208>'is already attached to session '1' (thisis'2')

PROBLEM SOLVING:

If you have db = SQLAlchemy(app) in, for example, text_file.py, and in app.py, you get this problem all time. You should del db = SQLAlchemy(app), and import db from app from app import db

Post a Comment for "Sqlalchemy Object Already Attached To Session"