Flask-SQLAlchemy how to delete all rows in one table

How to delete all rows in one 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 
+79
python flask flask-sqlalchemy sqlalchemy
May 15 '13 at 19:51
source share
3 answers

Try delete :

 models.User.query.delete() 

From the docs : Returns the number of rows deleted, excluding any cascades.

+123
May 15 '13 at 19:55
source share

DazWorrall's answer is the point. Here's an option that may be useful if your code is structured differently than OP:

 num_rows_deleted = db.session.query(Model).delete() 

In addition, do not forget that the deletion will not take effect until you commit, as in this fragment:

 try: num_rows_deleted = db.session.query(Model).delete() db.session.commit() except: db.session.rollback() 
+80
Aug 21 '14 at 19:28
source share

Flask-SQLAlchemy

 #for all records db.session.query(Model).delete() db.session.commit() 

here DB is an object of the Flask-SQLAlchemy class. It will delete all entries from it, and if you want to delete specific entries, try the filter clause in the query. e.g.

 #for specific value db.session.query(Model).filter(Model.id==123).delete() db.session.commit() 
+39
Jul 13 '16 at 7:06
source share



All Articles