Django 迁移 - 如何让它忘记?

Django migrations - how to make it forget?

我一直在草拟一个新的 Django 应用程序,在后台使用 runserver 开发服务器 运行 window 来跟踪网络布线,简要地我的模型中有这个:

class Interface(models.Model):
    name = models.CharField(max_length=200)
    # (blah)

class Connection(models.Model):
    interface_from = models.ForeignKey(Interface, related_name="connections")
    interface_to = models.ForeignKey(Interface, related_name="connections")
    source = models.CharField(max_length=32)

在我意识到我不能对两个字段使用相同的 related_name 之前。我想我需要写一些特别的东西来找到与接口相关的所有连接,因为它们可能是连接的 'to' 或 'from' 端(对任何更好的方法感兴趣那 - 就像一个 "Set" 字段)

此时,我还没有进行 makemigrations,但是在停止服务器并进行迁移时,我得到:

ERRORS:
autodoc.Connection.interface_from: (fields.E304) Reverse accessor for 'Connection.interface_from' clashes with reverse accessor for 'Connection.interface_to'.
HINT: Add or change a related_name argument to the definition for 'Connection.interface_from' or 'Connection.interface_to'.

即使没有冲突了。我在任何地方都看不到迁移目录 - 这是模型的初始传递 - 那么在开发服务器重新启动后,这个错误的内存来自哪里?

编辑:为了更清楚,我的连接模型现在看起来像:

class Connection(models.Model):
    interface_from = models.ForeignKey(Interface)
    interface_to = models.ForeignKey(Interface)
    source = models.CharField(max_length=32)

如果您不需要向后关系,请将 related_name='+' 添加到您的字段定义中。来自 doc

user = models.ForeignKey(User, related_name='+')

在你的第一个例子中:

class Connection(models.Model):
    interface_from = models.ForeignKey(Interface, related_name="connections")
    interface_to = models.ForeignKey(Interface, related_name="connections")

您要告诉 Django 在 Interface 上创建两个不同的 connections 属性,用于返回到 Connection 的后向关系,这显然不起作用。

在你的第二个例子中:

class Connection(models.Model):
    interface_from = models.ForeignKey(Interface)
    interface_to = models.ForeignKey(Interface)

您告诉 Django 将 its default connections_set name 用于返回到 Connection 的两个不同属性,这也不起作用。

修复方法是使用 related_name='+'(如 )完全禁用向后关系,或者两个显式提供两个不同的 related_name 属性,以便向后关系属性的名称不'冲突。