Menu

Adding a Required Foreign Key to a Table That Already Has Rows: A Safe Alembic Migration
📰

Adding a Required Foreign Key to a Table That Already Has Rows: A Safe Alembic Migration

DEV Community: flask·ByteBridge Talent LLC·17 days ago
#6lW75HSG
#devtoflask#devto#dev#alembic#users
Long article (2194 words) — no AI summary yet.
Reading 0:00
15s threshold

The problem

A developer in an online forum had a working app with two tables, users and images , both full of data. They wanted every image to belong to a user. So they added a foreign key from images to users , marked it "not null", and generated a migration with Flask-Migrate (which uses Alembic).

Before running flask db upgrade , they asked a fair question. What happens to the rows that are already there? Will the upgrade delete them? Will the new rule just skip the old rows? And how do you change a database that people are already using?

This post answers all three, with code we ran on SQLite.

The root cause

A migration changes the shape of the database. It does not invent data. A new column on a full table starts out empty ( NULL ) in every old row. A "not null" rule says the column can never be empty. Both cannot be true at once, so the database refuses the change.

Alembic's autogenerate cannot fix this for you. It compares your models with the database and writes the shape change.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.