python + SQLAlchemy:使用 Session 对象删除

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26643727/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:48:13  来源:igfitidea点击:

python + SQLAlchemy: deleting with the Session object

pythonsqlalchemy

提问by Wells

I can't quite figure this out: I'd like to delete all the records from a table on a matching query. Kind of like this.

我不太明白这一点:我想从匹配查询的表中删除所有记录。有点像这样。

engine = sqlalchemy.create_engine(string)
meta = MetaData(bind=engine)
meta.reflect(bind=engine, schema='myschema')

Base = automap_base(metadata=meta)
Base.prepare(engine, reflect=True)
Classes = Base.classes

Session = sessionmaker(bind=engine)
session = Session()

session.delete(plays.record_id == '123')

But that isn't working. What's the idea here? Error I get is:

但这不起作用。这里的想法是什么?我得到的错误是:

error in parsing record ID 020087: Class 'sqlalchemy.sql.elements.BinaryExpression' is not mapped

error in parsing record ID 020087: Class 'sqlalchemy.sql.elements.BinaryExpression' is not mapped

回答by muthan

In SQL Alchemy you are deleting Objects that you get with a query from the database. This you can do in 2 Ways:

在 SQL Alchemy 中,您正在删除通过查询从数据库中获得的对象。您可以通过 2 种方式执行此操作:

Deleting with query (will issue just one DELETEstatement):

使用查询删除(将只发出一个DELETE语句):

session.query(User).filter(User.id==7).delete()
session.commit()

Deleting object instance returned by a query (will issue 2 statements: first SELECT, then DELETE):

删除查询返回的对象实例(将发出 2 个语句: first SELECT, then DELETE):

obj=session.query(User).filter(User.id==7).first()
session.delete(obj)
session.commit()

回答by anand tripathi



Delete All Records

删除所有记录

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

Deleted Single Row

删除的单行

If you want to delete specific records then try filterclause in the query. ex.

如果要删除特定记录filter,请在查询中使用try子句。前任。

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

Delete Single Record by Object

按对象删除单条记录

record_obj = session.query(Model).filter(Model.id==123).first()
session.delete(record_obj)
session.commit()

https://flask-sqlalchemy.palletsprojects.com/en/2.x/queries/#deleting-records

https://flask-sqlalchemy.palletsprojects.com/en/2.x/queries/#deleting-records