Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
120 views
in Technique[技术] by (71.8m points)

python + SQLAlchemy: deleting with the Session object

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

question from:https://stackoverflow.com/questions/26643727/python-sqlalchemy-deleting-with-the-session-object

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Deleting with query (will issue just one DELETE statement):

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...