Django is a brilliant Python framework for the rapid development of web apps that helps to maintain a clean and pragmatic codebase. Although I have not been using Django until last year, I have to admit, as compared to Flask, Django is certainly much helpful with all the plugins that are available.

Django provides a comfortable way to manage the database using its migration feature, which is pretty straightforward. But if an implementation (or app) already has models and database tables without existing migrations, or the migrations get messed up (likely to happen), then using Django can be…painful. Indeed, this has been a rather frustrating issue that I had faced multiple times, and after some playing around, I found a working fix. The steps described below basically require dropping a table called django_migration that corresponds to all the migrations created with Django, then removing all the migration files in the project, resetting the migration, and re-creating them.

  1. Deleting the django_migration table Simply go to the corrposinding connected database and delete all the records from the django_mogrations table. If you are using a pssql, a simple DROP table will do the trick.

  2. Remove the local migration files You can manually remove all the migrations folders within your project or simply run rm -rf /migrations/. If the project has multiple apps within it, then the command find . -path "*/migrations/*.py" -not -name "__init__.py" -delete would assist in quickly removing all the relevant migration files.

  3. Reset the migrations Reset all the migrations of the Django app using the inbuilt feature python manage.py migrate —fake

  4. Re-create the migrations Now re-create the project’s migrations using python manage.py makemigrations. Special care is to be taken in this step if there are multiple apps in the project since the models with ForeginKey must be run only after the migrations for the parent model have been generated.

  5. Create the fake initial migrations Finally, push all your migrations while passing in the fake migration flag by running the command python manage.py migrate —fake-initial.

This would solve most of the Django migration mess up or allow starting from scratch for pre-existing databases. After the steps, its only matter for using the Django migration system as usual, i.e., once new fields have been added to the model or existing one altered, running the standard python manage.py makemigrations to create the migrations and python manage.py migrate to finalize the migrations.