Search code examples
pythondjangodjango-modelsdjango-migrations

FieldDoesNotExist with ManytoMany field


I have an issue while running migrations, I get this error :

django.core.exceptions.FieldDoesNotExist: Profile has no field named 'following

yet I have defined the field in my model, what could be the issue ?

below is my model :

class Profile(TimeStampedModel, models.Model):
    
    last_name = models.CharField(_('Last Name'), max_length=150,
                                 null=True, blank=True)
 
    gender = models.CharField(_('Gender'), null=True, max_length=30,
                              choices=GENDER_CHOICES, blank=True)
    following = models.ManyToManyField(User, related_name='following',
                                       default=None, blank=True)

What could be the issue ?

EDIT

Below is the stack trace :

https://gist.github.com/huxaiphaer/abd376f43d50625bd3b10fa4829d6b0e

Migration file :

from django.conf import settings
from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('profiles', '0013_auto_20211108_1641'),
    ]

    operations = [
        migrations.AddField(
            model_name='profile',
            name='following',
            field=models.ManyToManyField(blank=True, default=None,
                                         related_name='following',
                                         to=settings.AUTH_USER_MODEL),
        )
    ]

file : 0013_auto_20211108_1641

from django.conf import settings
from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('profiles', '0012_auto_20211108_0608'),
    ]

    operations = [
        migrations.AlterField(
            model_name='profile',
            name='following',
            field=models.ManyToManyField(blank=True, default=None, null=True, related_name='following', to=settings.AUTH_USER_MODEL),
        ),
    ]

Solution

  • You probably made a migration 0013 when you already had a following field, and thus that resulted in an AlterField migration, for a many-to-many relation that was not (yet) constructed by the migration.

    You can fix the 0013 migration file by removing the AlterField operation, and thus making it a a "no-op migration":

    from django.conf import settings from django.db import migrations, models

    class Migration(migrations.Migration):
    
        dependencies = [
            migrations.swappable_dependency(settings.AUTH_USER_MODEL),
            ('profiles', '0012_auto_20211108_0608'),
        ]
    
        operations = []

    This then will result in the migrations running again.

    I would however advise not to remove migrations in the future. Usually it only results in problems to get the migrations back on track.