Create Migrations For Existing Database Schema In Django

Ahmad Al-Sajid
2 min readMay 29, 2019

Though Django is a very handy and robust tool for web developments, sometimes we face such situations when we think, “am I doing right by using Django?”. Don’t about others, but, such thinking comes to my mind often when I have to integrate an existing database(maybe a copy from another developer/production database) with the Django project or I accidentally deleted the migrations files. As Django keeps track of the migrations in django_migrations table, most of the times it may mismatch with your local migrations. So, what we can do to resolve this conflict? The best way is to fake migrations. To do so, we will follow the below steps.

Empty the django_migrations table by running this command in SQL:

delete * from django_migrations;

Then, remove all migrations from every app except the __init__.py file from the migrations folder by running the command in CLI:

find ! -name '__init__.py' -type f -exec rm -f {} +

After that, we have to reset the migrations for the built-in apps by running:

python manage.py migrate --fake

Now, we have to create initial migrations for every app. Make sure to take care of the dependencies, i.e. models with ForeignKey’s should run after their parent model. We will do this by:

python manage.py makemigrations <app>

Finally, we will run:

python manage.py migrate --fake

This will finally sync the migrations with django_migrations and after this, we can use the migrations system normally.

N.B. We are using python3.6 and django 2.1 . If you are using Django ≤1.8, you have to replace --fake with --fake-initial .

I have taken this solution from StackOverflow.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Ahmad Al-Sajid
Ahmad Al-Sajid

Written by Ahmad Al-Sajid

Software Engineer, DevOps, Foodie, Biker

No responses yet

Write a response