繁体   English   中英

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迁移

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

这适用于Django 1.10

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM