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

后端 未结 3 679
礼貌的吻别
礼貌的吻别 2020-12-08 00:10

How do I delete all rows in a single table using Flask-SQLAlchemy?

Looking for something like this:

>>> users = models.User.query.all()
>         


        
相关标签:
3条回答
  • 2020-12-08 00:21

    Try delete:

    models.User.query.delete()
    

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

    0 讨论(0)
  • 2020-12-08 00:25

    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()
    
    0 讨论(0)
  • 2020-12-08 00:33

    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

    0 讨论(0)
提交回复
热议问题