Stuck in a django migration IntegrityError loop: can I delete those migrations that aren't yet in the db?
<p>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 <code>IntegrityError</code> (<code>django.db.utils.IntegrityError: insert or update on table "foo" violates foreign key constraint "bar"</code>). I ran <code>python manage.py makemigrations</code>, <code>python manage.py migrate</code>, which causes the the <code>IntegrityError</code>.</p>

<p>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 <code>select * from django_migrations;</code>, the latest db migration: <strong>0020</strong> there is eight migrations away from my latest local <code>home/migrations</code> migration file: <strong>0028</strong>.</p>

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

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

<p>Possible reasons of why you run into this error are:</p>

<ol>
<li>You deleted your model code but, when you run <code>migrate</code> it reads your migration files (which has information about your deleted model) and tries to apply migration operations. If you didn't run <code>makemigrations</code> 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. </li>
<li>Even if you've run <code>makemigrations</code> 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)</li>
</ol>

<p>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.</p>

<p>This <a href="https://docs.djangoproject.com/en/1.10/topics/migrations/#history-consistency" rel="nofollow">documentation</a> information maybe useful.</p>

python django