gpt4 book ai didi

python - 如何在 SQLAlchemy Alembic 迁移中更新记录?

转载 作者:行者123 更新时间:2023-11-29 07:01:21 32 4
gpt4 key购买 nike

我正在为我的 SQLAlchemy 应用程序编写数据库迁移脚本。下面的迁移有效。但它实际上并没有做任何事情(还!):

 1: from alembic import op
2: import sqlalchemy as sa
3:
4: def upgrade():
5: my_table = sa.Table('my_table',
6: sa.MetaData(),
7: sa.Column('my_id', sa.Integer, primary_key=True),
8: sa.Column('my_attribute1', sa.Text(), nullable=True),
9: sa.Column('my_attribute2', sa.String(length=128), nullable=True))
10:
11:
12: connection = op.get_bind()
13: for my_record in connection.execute(my_table.select()):
14: x = my_record.my_id
15: print x

我想修改上述迁移以执行以下操作,但我不知道如何操作:

  • 在第 13 行中,我只想选择 my_attribute1 == 'Hello' 的记录
  • 在第 15 行中,我不想执行打印语句,而是更新 my_record,将 my_attribute2 设置为 my_attribute1[:10] + 'Goodbye '

我该怎么做?当我尝试使用 where 子句进行选择和更新时,它们不起作用。 manual没有多大帮助。

最佳答案

在迁移中绕过 ORM 并执行类似的操作会更安全

connection = op.get_bind()
connection.execute("UPDATE my_table SET my_attribute2 = SUBSTRING(my_attribute1, 0, 10) + 'Goodbye' WHERE my_attribute1 = 'Hello'")

我假设这只是一个示例,您将做一些不同的事情,因为否则,您不需要采用 my_attribute1 的子字符串,因为它对于这些记录始终具有相同的值“Hello”。

关于python - 如何在 SQLAlchemy Alembic 迁移中更新记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43359406/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com