Flask-SQLAlchemy how to delete all rows in a single table

PythonSqlalchemyFlask Sqlalchemy

Python Problem Overview


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

Python Solutions


Solution 1 - Python

Try delete:

models.User.query.delete()

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

Solution 2 - Python

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()

Solution 3 - Python

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

Solution 4 - Python

writing raw sql commands sometimes is useful

    def delete_table_content(self, table_name: str):
          "deletes table contents"
          CONNECTION = db_url
          conn = psycopg2.connect(CONNECTION)
          conn.autocommit = True
          cursor = conn.cursor()
          cursor.execute("TRUNCATE TABLE {}".format(table_name))
          logger.warning("deleted table {} content".format(table_name))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSeanPlusPlusView Question on Stackoverflow
Solution 1 - PythonDazWorrallView Answer on Stackoverflow
Solution 2 - PythonSteve SaportaView Answer on Stackoverflow
Solution 3 - PythonAnand TripathiView Answer on Stackoverflow
Solution 4 - PythonMohamed MosȜdView Answer on Stackoverflow