How to force migrations to a DB if some tables already exist in Django

Python Eshan Ahmed

Problem

We have a database where it has correct tables and the code is up to date. But the migration folder is not up to date. After altering the models we face a problem while making migrations to the database where some tables already exist. While giving ‘makemigrations’ command migrations are created but it creates new tables along with the existing table. After that when we try to migrate with the ‘migrate’ command it says that the table we are trying to create already exists. We are going to solve this problem step by step.


Solution 1 (Recommended)

Here we will use custom SQL to solve this not through Django’s ORM.

First, run this command

manage.py sqlmigrate > mychanges.sql

This will create a 'mychanges.sql' file that contains all the SQL. Here you can now remove the changes that have been already performed and keep the rest that needs to be done. Now execute the SQL using 'Pgadmin'.You can also use 'psql' if you are PostgreSQL. After the changes have been made you can run

manage.py migrate --fake

This will sync the Django with what we want. This is the recommended way to do solve this problem. You can easily solve this if you have sufficient SQL skills.


Solution 2

With this method, we will not run any new 'makemigrations' and 'migrate' commands before. Now comment out all the new changes in the models.py that you wanted. Keep everything as it is in the database.

After that run 'makemigrations' and 'migrate “appname” --fake' command. This will bring things back in sync. Then uncomment the code you commented and again run 'makemigrations' and 'migrate' command. You will be able to see all the changes you made. This is going to work for small changes. If changes are big this method is not suggested.

Thanks for reading till the end. Please comment below If you have any further queries.