如何使用Flask-SQLAlchemy删除单个表中的所有行?
寻找这样的事情:
>>> users = models.User.query.all()
>>> models.db.session.delete(users)
# but it errs out: UnmappedInstanceError: Class '__builtin__.list' is not mapped
如何使用Flask-SQLAlchemy删除单个表中的所有行?
寻找这样的事情:
>>> users = models.User.query.all()
>>> models.db.session.delete(users)
# but it errs out: UnmappedInstanceError: Class '__builtin__.list' is not mapped
Answers:
尝试delete
:
models.User.query.delete()
从文档:Returns the number of rows deleted, excluding any cascades.
Model.query.filter(Model.some_id == some_id, Model.other_id.in_(other_ids).delete()
Flask-SQLAlchemy
则尝试User.query.delete()
作为query
对象,因为“ BaseQuery”对象不可调用。经过测试和验证。
删除所有记录
#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
models.User.query().delete()