JohnGalt
JohnGalt

Reputation: 897

Django cannot delete custom field class; makemigrations throws AttributeError

Lead-up:

I subclassed django.db.models.fields.CharField. Then used that custom field called myapp.models.QueryStringField in a model and made my migrations and migrated successfully. Then I changed my mind and decided to replace it with a normal CharField in my model, which I did (again with successfull migration).

Problem:

When I then deleted the QueryStringField class entirely from myapp.models and did makemigrations, it threw the following error (last lines shown here):

File "C:\...\migrations\00....py", line 17, in Migration
    field=myapp.models.QueryStringField(max_length=255),
AttributeError: module 'myapp.models' has no attribute 'QueryStringField'

What can I do to fix this? I understand that this is technically correct, since the migration references a class that is not present, but surely this can be solved somehow. I am a little nervous about just deleting migration files.

Upvotes: 2

Views: 949

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476709

You can not just delete a field class, that class is referenced by the migration files.

You should change the migration files where the QueryStringField is involved. You can inspect the migration where you changed the field, and remove that part of the migration, so:

from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ('someapp', '1234_some_name'),
    ]

    operations = [
        # migrations.AlterField(
        #     model_name='mymodel',
        #     name='myfield',
        #     field=models.QueryStringField(
        #         # ...
        #     ),
        # ),
    ]

as well as in the migration where you change it back:

from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ('someapp', '5678_some_other_name'),
    ]

    operations = [
        # migrations.AlterField(
        #     model_name='mymodel',
        #     name='myfield',
        #     field=models.CharField(
        #         # ...
        #     ),
        # ),
    ]

After you removed these changes (and all changes that thus work with the QueryStringField), you can safely remove it.

Upvotes: 3

Related Questions