Flask-SQLAlchemy how to delete all rows in a single table
Flask-Sqlalchemy
Delete All Records
#for all records
db.session.query(Model).delete()
db.session.commit()
Deleted Single Row
here DB is the object Flask-SQLAlchemy class. It will delete all records from it and if you want to delete specific records then try filter
clause in the query.
ex.
#for specific value
db.session.query(Model).filter(Model.id==123).delete()
db.session.commit()
Delete Single Record by Object
record_obj = db.session.query(Model).filter(Model.id==123).first()
db.session.delete(record_obj)
db.session.commit()
https://flask-sqlalchemy.palletsprojects.com/en/2.x/queries/#deleting-records
Try delete
:
models.User.query.delete()
From the docs: Returns the number of rows deleted, excluding any cascades.
DazWorrall's answer is spot on. Here's a variation that might be useful if your code is structured differently than the OP's:
num_rows_deleted = db.session.query(Model).delete()
Also, don't forget that the deletion won't take effect until you commit, as in this snippet:
try:
num_rows_deleted = db.session.query(Model).delete()
db.session.commit()
except:
db.session.rollback()