Django 1.8 Circular Dependecy error

2019-06-10 02:18发布

问题:

I'm having trouble finding solutions to this problem online. All I have is "To manually resolve a CircularDependencyError, break out one of the ForeignKeys in the circular dependency loop into a separate migration, and move the dependency on the other app with it. If you’re unsure, see how makemigrations deals with the problem when asked to create brand new migrations from your models. In a future release of Django, squashmigrations will be updated to attempt to resolve these errors itself." from here: docs . I'm kind of new to django migrations, I'd love a more comprehensible and easy to follow answer.

I get this error:

raise CircularDependencyError(", ".join("%s.%s" % n for n in cycle))
django.db.migrations.graph.CircularDependencyError: libros.0001_initial, perfiles.0001_initial

I don't know how to find where is the CircularDependency and I'm not sure how to solve it. As you can see, the migrations are n001 - that's because I tried erasing them and doing it again, didn't work. Please help.

回答1:

You should create one migration without foreign key and add the FK later.

Lets suppose that you want to create these models:

libros/models.py:

class Libro(models.Model):
    name = models.CharField(max_length=20)
    perfile = models.ForeignKey('perfiles.Perfile', null=True)

perfiles/models.py:

class Perfile(models.Model):
    name = models.CharField(max_length=20)
    libro = models.ForeignKey('libros.Libro', null=True)

Of course you can't do it because of the circular dependency. So comment out foreign key in the Libro model:

class Libro(models.Model):
    name = models.CharField(max_length=20)
    # perfile = models.ForeignKey('perfiles.Perfile', null=True)

And run two migrations:

python manage.py makemigrations libros
python manage.py makemigrations perfiles

After that uncomment the perfile foreign key in the Libro model and run another migration:

python manage.py makemigrations libros


回答2:

To those who have encountered CircularDependencyError - not necessarily with ForeignKey - It is good to go to the cycles

python manage.py makemigrations app_name; python manage.py migrate

for each application in your project, one by one.

this has worked for Django 1.10