Hillary Sanders
Hillary Sanders

Reputation: 6047

Stuck in a django migration IntegrityError loop: can I delete those migrations that aren't yet in the db?

So, I committed and pushed all my code, and then deployed my web application successfully. Then, I added a new model to my 'home' app, which (for a reason I now understand, but doesn't matter here), created an IntegrityError (django.db.utils.IntegrityError: insert or update on table "foo" violates foreign key constraint "bar"). I ran python manage.py makemigrations, python manage.py migrate, which causes the the IntegrityError.

However, even if I remove all of my new model code(so that git status comes up with nothing), the IntegrityError still happens. If I connect to my db via a different python instance and download select * from django_migrations;, the latest db migration: 0020 there is eight migrations away from my latest local home/migrations migration file: 0028.

--> My question is: is it safe for me to delete my local 0021-0028 migration files? Will this fix my problem?

Upvotes: 2

Views: 899

Answers (2)

sehrob
sehrob

Reputation: 1044

If you haven't applied your migrations to db, it is safe to delete them and recreate them.

Possible reasons of why you run into this error are:

  1. You deleted your model code but, when you run migrate it reads your migration files (which has information about your deleted model) and tries to apply migration operations. If you didn't run makemigrations command after you've deleted your model, migration system won't be able to detect your changes and will think that your model is still there.
  2. Even if you've run makemigrations after you've deleted your model there'll be dependency issues in your migrations files, because the new migration files will depend on old ones (with which you had problems)

That's why we can say that it is safe to delete them, if they haven't applied, but at the same time you should be careful with your migration dependencies.

This documentation information maybe useful.

Upvotes: 2

Hillary Sanders
Hillary Sanders

Reputation: 6047

OK, so I crossed my fingers, backed my local 0021-0028 migration files, and then deleted them. It worked. I think they key is that the migration files were not yet in the database yet, but not 100% sure. +1 if anyone can answer further for clarification.

Upvotes: 0

Related Questions