Search code examples
pythondjangodjango-migrations

Django migration fails to remove field


I'm using Python 3.8.4, Django 2.2.3, SQLite 3.32.3.

When I run python manage.py makemigrations, Django creates a migration file containing the following operation, among others which execute successfully).

migrations.RemoveField(
    model_name='essayrequirement',
    name='program',
),

The program field's declaration before it is removed is as follows:

program = models.ForeignKey(UndergraduateProgram, on_delete=models.CASCADE, related_name="essay_set", null=True, blank=True)

However, when I try to run the migration (python manage.py migrate), I get the error django.core.exceptions.FieldDoesNotExist: NewEssayRequirement has no field named 'program'. (It seems NewEssayRequirement is a temporary table created in the course of applying the migration, which should replace the EssayRequirement table before the migration is complete.)

Poking around in the SQLite database itself before applying the migration confirms that the program field did in fact exist -- the column for it exists. In addition, I've tried removing this operation from the migration, and of course the next call to makemigrations brings it back. The same error occurs when migrateing in this case.

Interestingly enough, there was another field called non_undergrad_program on the same model, differing only in where the ForeignKey points to. The migration in question also removes this field, but for some reason does so successfully:

migrations.RemoveField(
    model_name='essayrequirement',
    name='non_undergrad_program',
),

I've been stuck on this issue for a while, as it more or less breaks the migrations in our app moving forward. I can't even find a way to ignore the operation, and proceed forward ignoring that column's existence.


Solution

  • Turns out it was due to a uniqueness constraint on the field I had deleted, which I had overlooked:

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['program', 'index'], name='unique_essay')
        ]
    

    This constraint was the source of the FieldDoesNotExist exception. The issue was resolved by adjusting the constraint list and remaking migrations, then adding those generated operations to the problematic migrations file.