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.
You need to append each item in your result to the movie.formats
relation.
for format in formats:
movie.formats.append(format)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With