Reputation: 12635
I'm writing a Database Migration script for my SQLAlchemy application. The migration below works. But it doesn't actually do anything (yet!):
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
I want to modify the above migration to do the following things but I don't know how:
my_attribute1
== 'Hello'
my_record
such that my_attribute2
is set to my_attribute1[:10] + 'Goodbye'
How can I do it? When I tried to do selects & updates with where clauses, they didn't work. The manual wasn't much help.
Upvotes: 0
Views: 4523
Reputation: 3305
It would be safer for you to bypass ORM in migrations and just do something like
connection = op.get_bind()
connection.execute("UPDATE my_table SET my_attribute2 = SUBSTRING(my_attribute1, 0, 10) + 'Goodbye' WHERE my_attribute1 = 'Hello'")
I assume this is just an example and you're going to do something a bit different, because otherwise, you wouldn't need to take the substring of my_attribute1 as it always has the same value 'Hello' for those records.
Upvotes: 4