Relation does not exist, in PostgreSQL, Django

Viewed 611

So I've created a new model in Django, then executed both python manage.py makemigrations and python manage.py migrate in the right order. But then for some reason I accidentally dropped the table(relation) in PgAdmin (I know it sounds silly). So I tried deleting all the files in migrations folder but the init.py file. Then I ran the two commands above again, but could see no table in the PgAdmin.
What should I do, aside from creating a table myself in PgAdmin?

Thanks in advance.

2 Answers

It won't work, because entry for all the migrations are already stored inside a table named django_migrations. So even if you run makemigrations after deleting all the migration files, it won't create a new one. So here is three ways you can fix it.

One: Drop DB(if data is not important)

Drop database and create a new one. Run makemigrations and migrate command.

Two: Create that table manually

If you already deleted all the migration files, you better restore them. You can use git for this: git checkout /path/to/migration/folder. Then you can manually create the table.

Three: Delete entries from django_migrations

I assumed you have deleted all the migration files. So this part covers the whole project. But @DenizKaplan has explained better way to do this.

If you are not using git, or no way to restore these files, then you can follow these steps:

  1. Backup your database
  2. Delete all entries from djang_migrations table
  3. Run ./manage.py makemigrations to generate migration file
  4. Run ./manage.py migrate <your lost app> to migrate your app(which you have lost in DB).
  5. Run ./manage.py migrate --fake to fake the rest of apps.

There are some steps you need to check. If you have an empty output after makemigrations operations, you may need to check for django_migrations table to remove rows related to apps that you have working with. If this won't help at first place, you need check INSTALLED_APPS, maybe you may accidently delete apps. If all these not work, please give some detailed information about the error.

Related