Search code examples
djangodjango-modelsdjango-migrations

ValueError: Related model u'app.model' cannot be resolved


I have two applications (ook and eek say) and I want to use a foreign key to a model in ook from a model in eek. Both are in INSTALLED_APPS with ook first.

In ook.models.py, i have:

class Fubar(models.Model):
    ...

In eek.models.py, I have:

class monkey(models.Model):
    external = models.ForeignKey('ook.Fubar', blank=True, null=True)
    ...

The migration generated is:

class Migration(migrations.Migration):

    dependencies = [
        ('eek', '0002_auto_20151029_1040'),
    ]

    operations = [
        migrations.AlterField(
            model_name='monkey',
            name='external',
            field=models.ForeignKey(blank=True, to='ook.Fubar', null=True),
        ),
    ]

When I run the migration, I get this error:

   ...
   1595             raise ValueError('Foreign Object from and to fields must be
the same non-zero length')
   1596         if isinstance(self.rel.to, six.string_types):
-> 1597             raise ValueError('Related model %r cannot be resolved' % self.rel.to)
   1598         related_fields = []
   1599         for index in range(len(self.from_fields)):
ValueError: Related model u'ook.Fubar' cannot be resolved

What am I doing wrong?


Solution

  • Because You have ForeignKey in operations, You must add a ook to dependencies:

    dependencies = [
        ('ook', '__first__'),
        ('eek', '0002_auto_20151029_1040'),
    ]
    

    Django migrations have two "magic" values:

    • __first__ - get module first migration
    • __latest__ - get module latest migration