SQLAlchemy A conflict state is already present in the identity card for the key

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

I have a many-to-many relationship between the Format and Film models. I successfully established a relationship and fulfilled the queries without any problems. The problem occurs when I try to make an update in movie formats. Calling the update method results in an 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 being deleted / cleared properly between / db update requests, but adding a remove () call does not 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 understanding will be greatly appreciated! I tried many SqlAlchemy methods with no luck (excluding platforms, merging a movie object, deleting a session, etc.). I also tried setting movie formats to empty and making changes to db before adding new formats, but without changes.

+4
source share
1 answer

You need to add each element to your result in movie.formats .

 for format in formats: movie.formats.append(format) 
+1
source

All Articles