在SQLAlchemy中选择行,进行更改和更新数据库

2024-05-03 09:02:24 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我的表只有两列:

  • 身份证
  • 步骤编号
  • 开始日期

我想选择step_id == 2所在的行,并将start_date(当前为空)更新为当前时间。目前,我正在做的是:

engine = create_engine('postgresql://postgres:postgres@localhost/quantdb')
metadata = MetaData(bind=engine)
step_instance = Table('step_instance', metadata, autoload=True)

s = step_instance.select().where(step_instance.c.step_id == 2)
res = engine.execute(s)

for row in res:
    start_date_stmt = step_instance.update().where(step_instance.c.id == row.id).\
        values(start_date=datetime.now(pytz.utc))

    engine.execute(start_date_stmt)

这感觉很笨拙,有更好的方法吗?我在考虑在哪里可以直接修改row中的字段,然后用这个修改后的row来“更新”数据库。在

有可能吗?也很高兴听到其他更好的方法。在


Tags: 方法instanceidexecutedatesteprespostgres
1条回答
网友
1楼 · 发布于 2024-05-03 09:02:24

是的,你可以。查找会话。我还没有测试下面的样本,但它给了你一个做什么的想法。在

...
db_session = scoped_session(sessionmaker(bind=engine))
res = db_session.query(step_instance).filter(step_instance.c.step_id == 2)
for row in res:
    row.start_date = datetime.now(pytz.utc)
db_session.commit()

相关问题 更多 >