How to recreate a deleted table with Django Migrations?
In django 1.7 you can try:
1. Delete your migrations folder
2. In the database: DELETE FROM django_migrations WHERE app = 'app_name'.
You could alternatively just truncate this table.
3. python manage.py makemigrations
4. python manage.py migrate --fake
If you are working in django 1.9.5 this is the 100 % solution for this problem:
1. Delete your migrations folder
2. In the database: DELETE FROM django_migrations WHERE app = 'app_name'.
You could alternatively just truncate this table.
3. python manage.py makemigrations app_name
4. python manage.py migrate
This works 100% for me!
The only way that worked for me:
rm -r <app-name>/migrations/
python manage.py makemigrations <app-name>
python manage.py sqlmigrate <app-name> 0001_initial
Copy what it prints out (or, depending on what you have actually removed from the DB, only part of the SQL queries).
Apply those copied queries to your DB:
psql -U user_name -h 127.0.0.1 database_name
Paste what you have copied from the SQL queries printout.
Commit the queries.
And that's it - your missing tables are created.
There isn't an easy way to get Django to recreate a table that you have deleted manually. Once your database is altered manually, Django's view of the database (from migrations) is different from reality, and it can be tricky to fix.
If you run the sqlmigrate command, it will show you the required SQL to create the table. You can run the sql in a database shell. Assuming your app name is students
, and the migration that created the table was 00XX_create_students.py
, you would do:
./manage.py sqlmigrate students 00XX_create_students
Be careful if there are foreign keys to or from the students table, the constraints will have to be created as well.