Django循环依赖1

2024-05-16 12:38:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我在网上找不到这个问题的解决方案。我只有"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

我不知道如何找到循环依赖性在哪里,也不知道如何解决它。正如您所看到的,迁移是n001-这是因为我尝试删除它们,然后再次执行,但没有成功。请帮忙。在


Tags: ofthetodjangoinmigrationswith解决方案
2条回答

对于那些遇到过CircularDependencyError(不一定是用ForeignKey)的人来说,去循环是很好的

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

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

这对django1.10有效

您应该创建一个不带外键的迁移,然后添加FK。在

假设您要创建以下模型:

诽谤/py模型

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

不忠/py模型

^{pr2}$

当然,由于循环依赖,您不能这样做。所以在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

相关问题 更多 >