Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy A conflicting state is already present in the identity map for key

I'm using the Flask-SqlAlchemy extension around SQLAlchemy to work with a SQLite database in Python.

I have a many-to-many relationship set up between "Format" and "Movie" models. I have successfully set the relationship and performed queries with no problem. The problem occurs when I try to make an update to a movie's formats. Calling my update method results in a AssertionError: A conflicting state is already present in the identity map for key (<class 'moviecode.models.Format'>, (1,))

This error makes me think that the SQLAlchemy Session is not getting removed/cleaned up properly between the update calls/db queries, but adding a remove() call doesn't help.

mainapp.py

app = Flask('moviecode')
db = SQLAlchemy(app)

views.py

from updater import updateMovie

@app.route("/admin/movies/<int:movieId>/refresh/",methods=['GET'])
@login_required
def refreshMovie(movieId):
     updateMovie(movieId)
     return redirect(url_for('admin'))

updater.py

from mainapp import db
from models import Format, Movie

def updateMovie(movieId):
    movie = Movie.query.filter_by(id=movieId).first()
    formats = Format.query.all()
    movie.formats = newFormats #ERROR IS THROWN HERE
    db.session.commit()
    db.session.remove() #Trying to clean up Session. Makes no difference.

Any help or insight would be much appreciated! I've tried lots of SqlAlchemy methods with no luck (expunging the platforms, merging the movie object, removing the session, etc). Also tried setting the movies formats to blank and committing the change to the db before adding back the new formats, but no change.

like image 255
clamz Avatar asked Nov 12 '22 06:11

clamz


1 Answers

You need to append each item in your result to the movie.formats relation.

for format in formats:
    movie.formats.append(format)
like image 64
peterb Avatar answered Nov 14 '22 22:11

peterb