问题
How do I delete all rows in a single table using Flask-SQLAlchemy?
Looking for something like this:
>>> users = models.User.query.all()
>>> models.db.session.delete(users)
# but it errs out: UnmappedInstanceError: Class '__builtin__.list' is not mapped
回答1:
Try delete:
models.User.query.delete()
From the docs: Returns the number of rows deleted, excluding any cascades.
回答2:
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()
回答3:
Flask-Sqlalchemy
#for all records
db.session.query(Model).delete()
db.session.commit()
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()
来源:https://stackoverflow.com/questions/16573802/flask-sqlalchemy-how-to-delete-all-rows-in-a-single-table