Search code examples
pythonsqlalchemydatabase-migrationlowercasealembic

I have a database in sqlalchemy and I'm trying to change the values of a column in the database to lowercase during the database migration


The FeedSnapshot table has a column username whose values I want to force to all lowercase. Also when I try to use the update..set commnad, I get an error that 'update' has no attribute 'set'. Is there an equivalent of the command that I can use here?

Here is what I tried:

def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
session = Session(bind=op.get_bind())
session.autoflush = False
metadata = MetaData(bind=op.get_bind())

feed_snapshot = Table('FeedSnapshots', metadata, autoload=True)
# update(feed_snapshot).set(feed_snapshot.c.Username == feed_snapshot.c.Username.lower())\
#     .where(feed_snapshot.c.Username).upper()
session.query(feed_snapshot).filter(func.lower(feed_snapshot.c.Username))

def downgrade():
pass

Solution

  • Just figured out the solution. You need to use update_table_by_filed_name:

    def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    session = Session(bind=op.get_bind())
    session.autoflush = False
    metadata = MetaData(bind=op.get_bind())
    
    feed_snapshot = Table('FeedSnapshots', metadata, autoload=True)
    session.execute(update_table_by_field_name('FeedSnapshots', values={'Username': func.lower(feed_snapshot.c.Username)}, bind=op.get_bind()))
    session.commit()
    
    
    def downgrade():
    pass