DEV Community

sumandari
sumandari

Posted on

Flask-Migrate (SQLAlchemy) update length of String Field

I wanted to update the length of my string field model. But when I run flask db migrate it says:

"INFO [alembic.env] No changes in schema detected."

So here's how I updated my length of a string field in my SQLALchemy model (I used postgres for the database)

  • Create an empty migration file flask db revision -m "your migration message here". it created a new migration file with this content:
"""your migration message here

Revision ID: 24822ca23a29
Revises: c48c50454932
Create Date: 2023-07-20 23:37:28.918613

"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = '24822ca23a29'
down_revision = 'c48c50454932'
branch_labels = None
depends_on = None


def upgrade():
    pass


def downgrade():
    pass
Enter fullscreen mode Exit fullscreen mode

according to that file, if you run flask db current, it will return the down_revision value: c48c50454932.
And if you want to implement this specific migration file, you need to run flask db upgrade 24822ca23a29 which is the value of revision

  • Now, update the upgrade method with your expected string field properties. I wanted to update field my_field in tablename table in my database. The existing length was 20, and I wanted to make it 50. Null value is not allowed in my case.

def upgrade():
    op.alter_column('tablename', 'my_field',
                    existing_type=sa.String(length=20),
                    type_=sa.String(length=50),
                    existing_nullable=False)

Enter fullscreen mode Exit fullscreen mode
  • Always use downgrade method for the fallback just in case the migration doesn't work as expected.

basically, I just wanted to make the length back to the previous value. So I switched the existing_type and type_ value


def downgrade():
    op.alter_column('tablename', 'my_field',
                    existing_type=sa.String(length=50),
                    type_=sa.String(length=20),
                    existing_nullable=False)

Enter fullscreen mode Exit fullscreen mode
  • Run the flask db upgrade to implement this latest migration file in your database schema and run flask db downgrade to get the previous database schema.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay