-->
With an Example Fix: Flask Migrate is not Working in Sqlalchemy

With an Example Fix: Flask Migrate is not Working in Sqlalchemy

Back to top

Updated by Ashirafu Kibalama on June 01, 2024

With an Example Learn To Fix: Flask Migrate is not Working in Sqlalchemy



Flask Migrate simplifies managing database migrations in Flask applications. But, it can fail and impede progress. 

We investigate the core causes of Flask Migrate's malfunction and provide a step-by-step fix. 

By understanding the underlying mechanisms and troubleshooting techniques, you will be better skilled to handle similar challenges in your Flask projects.

8 Ways To Fix: Flask Migrate is not Working in Sqlalchemy.

This is the blog post model where I wanted to add a new column, "Add an update by on date flask python example," using Flask Migrate in SQLalchemy. However, it only worked once I found a solution.




Add An Update by on Date Column Flask Python Example.


update: Mapped[str] = mapped_column(String(250), nullable=False)



1) Ensure that you have installed Flask-Migrate and created the required configurations:


from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///your_database.db'

db = SQLAlchemy(app)
migrate = Migrate(app, db)


2) Flask db init:


Click here to Learn to fix: "Error: Could not locate a Flask application. Use the 'flask --app' option, 'FLASK_APP' environment variable, or a 'wsgi.py' or 'app.py' file in the current directory."




Click here to Learn to fix: Error: Directory migrations already exists and is not empty


3) Flask migrate -m:


ERROR [flask_migrate] Error: Can't locate revision identified by '1928a5ff5bc6'

2 Ways To Fix ERROR [flask_migrate] Error: Can't locate revision identified by '1928a5ff5bc6'


1- use flask db revision --rev-id revision number:

 flask db revision --rev-id revision number





2- Then flask db migrate and flask db upgrade:


Flask migrate -m is done as illustrated above.

And now ERROR [flask_migrate] Error: Can't locate revision identified by '1928a5ff5bc6' is fixed and solved.


4) Flask db upgrade:





If you encounter this: "sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) Cannot add a NOT NULL column with default value NULL

[SQL: ALTER TABLE blog_posts ADD COLUMN "update" VARCHAR(250) NOT NULL]"




3 Ways To Fix sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) Cannot add a NOT NULL column with default value NULL
[SQL: ALTER TABLE blog_posts ADD COLUMN "update" VARCHAR(250) NOT NULL]


1- Remove the words "nullable=False" from the model:



#after removing 



2- Go to migrations, then to the versions folder and open it: Open the created migration file.





3- Remove the words "nullable=False"  from the def upgrade():

#before change


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('blog_posts', schema=None) as batch_op:
batch_op.add_column(sa.Column('update', sa.String(length=250), nullable=False))

# ### end Alembic commands ###

#after change


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('blog_posts', schema=None) as batch_op:
batch_op.add_column(sa.Column('update', sa.String(length=250)))

# ### end Alembic commands ###


Now 

"sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) Cannot add a NOT NULL column with default value NULL

[SQL: ALTER TABLE blog_posts ADD COLUMN "update" VARCHAR(250) NOT NULL]"

is fixed and solved.


5) Again Flask db upgrade:





6) To learn how to migrate and upgrade whenever you make new changes, skip to step 8 or 8): 



7) Edit post code:

#main.py


## OTHER CODES ABOVE ###

def edit_post(post_id):
post = db.get_or_404(BlogPost, post_id)
edit_form = CreatePostForm(
title=post.title,
subtitle=post.subtitle,
meta_tag=post.meta_tag,
author=post.author,
body=post.body,
update=post.update

)
if edit_form.validate_on_submit():
post.title = edit_form.title.data
post.subtitle = edit_form.subtitle.data
post.meta_tag = edit_form.meta_tag.data
post.author = current_user
post.body = edit_form.body.data
post.update = date.today().strftime("%B %d, %Y")

## OTHER CODES ABOVE ###

#post.html


<span class="meta fst-italic">
{% if post.update %}
Updated by
<a href="#">{{ post.author.name }}</a>
on {{ post.update }}

{% else %}


Posted by
<a href="#">{{ post.author.name }}</a>
on {{ post.date }}

{% endif %}
</span>

#index.html

<p class="post-meta">
{% if post.update %}
Updated by
<a href="#">{{post.author.name}}</a>
on {{post.update}}
{% else %}
Posted by
<a href="#">{{post.author.name}}</a>
on {{post.date}}
{% endif %}


</p>


8) To Migrate and upgrade whenever you make new changes:


Let's add a new column to the Pages model above, i.e., an update column.

update: Mapped[str] = mapped_column(String(250))

class Pages(db.Model):
__tablename__ = "pages"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
title: Mapped[str] = mapped_column(String(400), unique=True, nullable=False)
subtitle: Mapped[str] = mapped_column(String(250), nullable=False)
image: Mapped[str] = mapped_column(String, nullable=False)
body: Mapped[str] = mapped_column(Text, nullable=False)
update: Mapped[str] = mapped_column(String(250))

1- Repeat flask migrate -m;



2- Repeat flask upgrade step 4) or 4):



Attention here:

Open the created migration file:




Note

#remove or delete nullable=False from the def upgrade(): from the pages and blog_posts:

# changes



def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('blog_posts', schema=None) as batch_op:
batch_op.alter_column('update',
existing_type=sa.VARCHAR(length=250),
)



with op.batch_alter_table('pages', schema=None) as batch_op:
batch_op.add_column(sa.Column('update', sa.String(length=250),))

# ### end Alembic commands ###


3- again flask db upgrade:





Running into issues with Flask Migrate in SQLAlchemy can be frustrating in Flask development. 


This blog post provides nine ways to troubleshoot and fix Flask Migrate issues. 


Each solution contributes to a comprehensive toolkit for overcoming SQLAlchemy integration hurdles through debugging techniques, configuration adjustments, and potential pitfalls.


Persistence and a systematic approach are key when troubleshooting technical issues. 


By diagnosing the problem, implementing targeted fixes, and thoroughly testing, you can resolve the issue with Flask Migrate and deepen your understanding of Flask and SQLAlchemy integration.


Refer back to these strategies whenever you encounter challenges with Flask Migrate. 


With perseverance and the right know-how, you can overcome any obstacles, ensuring smooth database migrations and seamless application deployment.


Let us know how helpful this post was or if there is anything you think we missed. Your feedback is valuable.


Thank you, and Happy coding!

Related Posts:

1) With an Example Fix: How To Delete Existing Migration Files Flask Python / Directory migrations already exists and is not empty


2) With an Example Fix: Sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) No Such Column:


3) Which is Better, SQLite or SQLAlchemy?


4) What Are The Purposes of Flask-SQLAlchemy in Python? 


5) When Should You Use SQLAlchemy? 


6) What are The Major Benefits of Using SQLAlchemy in Python?


7) What are The Differences Between Flask-SQLAlchemy and SQLAlchemy? 


8) What are The Disadvantages of Flask-SQLAlchemy?


9) Sqlalchemy-migrate vs Alembic 


10) Flask-migrate vs Alembic 

11) With an Example Fix: Database Configuration Postgresql Flask Example