Create Migrations For Existing Database Schema In Django
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.