Flask-SQLAlchemy如何删除单个表中的所有行

问题:Flask-SQLAlchemy如何删除单个表中的所有行

如何使用Flask-SQLAlchemy删除单个表中的所有行?

寻找这样的事情:

>>> users = models.User.query.all()
>>> models.db.session.delete(users)

# but it errs out: UnmappedInstanceError: Class '__builtin__.list' is not mapped

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

回答 0

尝试delete

models.User.query.delete()

文档Returns the number of rows deleted, excluding any cascades.

Try delete:

models.User.query.delete()

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


回答 1

DazWorrall的答案是正确的。如果您的代码结构不同于OP的结构,那么以下变体可能会很有用:

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

另外,不要忘记在您提交后删除操作才会生效,如以下代码段所示:

try:
    num_rows_deleted = db.session.query(Model).delete()
    db.session.commit()
except:
    db.session.rollback()

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

回答 2

烧瓶法术

删除所有记录

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

删除单行

DB是对象Flask-SQLAlchemy类。它将从中删除所有记录,如果要删除特定记录,则filter查询中的try 子句。例如

#for specific value
db.session.query(Model).filter(Model.id==123).delete()
db.session.commit()

按对象删除单个记录

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

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