Python Flask-SQLAlchemy 如何删除单个表中的所有行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16573802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Flask-SQLAlchemy how to delete all rows in a single table
提问by SeanPlusPlus
How do I delete all rows in a single table using Flask-SQLAlchemy?
如何使用 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
采纳答案by DazWorrall
回答by Steve Saporta
DazWorrall's answer is spot on. Here's a variation that might be useful if your code is structured differently than the OP's:
DazWorrall 的回答是正确的。如果您的代码结构与 OP 不同,这里有一个变体可能很有用:
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()
回答by anand tripathi
Flask-Sqlalchemy
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 filterclause in the query.
ex.
这里 DB 是 Flask-SQLAlchemy 类的对象。它将从中删除所有记录,如果要删除特定记录,则filter在查询中使用try子句。前任。
#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
https://flask-sqlalchemy.palletsprojects.com/en/2.x/queries/#deleting-records

