Django 1.8 循环依赖错误

Django 1.8 Circular Dependecy error

我无法在线找到此问题的解决方案。我只有 "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." 来自这里: docs 。我是 django 迁移的新手,我想要一个更易于理解和易于理解的答案。

我收到这个错误:

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

我不知道如何找到 CircularDependency 在哪里,我不确定如何解决它。如您所见,迁移是 n001 - 那是因为我尝试擦除它们并再次执行,但没有成功。请帮忙。

您应该创建一个没有外键的迁移,然后再添加 FK。

假设您要创建这些模型:

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)

当然你不能这样做,因为循环依赖。所以注释掉Libro模型中的外键:

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

和运行两次迁移:

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

之后取消注释 Libro 模型中的 perfile 外键和 运行 另一个迁移:

python manage.py makemigrations libros

对于那些遇到 CircularDependencyError - 不一定与 ForeignKey - 去循环是好的

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

对于项目中的每个应用程序,一个接一个。

这适用于 Django 1.10