PROJECTS NOTES HOME

Recreate manually deleted table in django

I was attempting to remove an app from django project and I uncommented the model file, then ran makemigrations and migrate. So changes in the DB have been made, uncommented tables were dropped.

I then realized I am in a wrong git branch. So I reverted the changes to the model file, changed branch and started the server. Database is the same, with no tables, but models show that there should be tables. Migration file also shows that there should be tables. When I tried to run makemigrations and migrate - nothing would happen. I had to find a way to recreate the deleted tables.

For that I found this command:

python manage.py migrate --fake app_name zero
python manage.py migrate app_name

So I ran in my case:

[nixos@nixos:~/GIT/lifeapi]$ python manage.py migrate --settings=settings.development --fake website_fixes_app zero
Operations to perform:
  Unapply all migrations: website_fixes_app
Running migrations:
  Rendering model states... DONE
  Unapplying website_fixes_app.0002_websitefix_user... FAKED
  Unapplying website_fixes_app.0001_initial... FAKED

So it unapplied the migrations from the two migration files, I then had this message when I ran the server:

You have 2 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): website_fixes_app. Run 'python manage.py migrate' to apply them.

Okay, great, let's run the migrations:

[nixos@nixos:~/GIT/lifeapi]$ python manage.py migrate --settings=settings.development
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, members_app, quiz_app, rescuetime_app, sessions, weather_app, website_fixes_app
Running migrations:
  Applying website_fixes_app.0001_initial... OK
  Applying website_fixes_app.0002_websitefix_user... OK

As you can see, the migrations were applied, so the tables were created in the DB!

Amazing :)