Thomas Thomas - 3 months ago 10
Python Question

Rows are still present after calling delete() in SQLAlchemy

I want to have a Flask route that deletes all instances of a SQLAlchemy model,

VisitLog
. I call
VisitLog.query.delete()
, then redirect back to the page, but the old entries are still present. There was no error. Why weren't they deleted?

@app.route('/log')
def log():
final_list = VisitLog.query.all()
return render_template('log.html', loging=final_list)

@app.route('/logclear')
def logclear():
VisitLog.query.delete()
return redirect("log.html", code=302)


<a href="{{ url_for('logclear') }}">Clear database</a>

Answer

Just like other write operations, you must commit the session after executing a bulk delete.

VisitLog.query.delete()
db.session.commit()
Comments