【问题标题】:Django migrations - how to make it forget?Django 迁移 - 如何让它忘记?
【发布时间】:2023-04-06 10:38:01
【问题描述】:

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

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 之前。我想我需要写一些特别的东西来查找与接口相关的所有连接,因为它们可能是连接的“到”或“从”端(有兴趣了解更好的方法来做到这一点 - 比如“设置”字段)

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

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)

【问题讨论】:

  • 更新后的Connection 模型是什么样的?
  • 更改related_name,不能相等
  • @JoshKelley - 为您更新了问题
  • @PauloPessoa - 我知道,这就是我再次删除它的原因! :-)
  • 尝试只在一个字段中添加related_name

标签: python django django-migrations


【解决方案1】:

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

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

【讨论】:

  • 没有这个,我会得到(大部分无用但无害)Interface.interface_from_set 和 Interface.interface_to_set 对吧?很高兴知道,一旦原始问题得到解决,它就可以被禁用...
【解决方案2】:

在你的第一个例子中:

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='+'(如@Ivan said)完全禁用反向关系,或者两个显式提供两个不同的related_name 属性,以便反向关系属性的名称不会冲突。

【讨论】:

  • D'oh - 由于某种原因,我认为它会使用字段名称而不是模型名称来表示反向关系。谢谢你的解释!
猜你喜欢
  • 2015-12-24
  • 2018-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-13
  • 1970-01-01
相关资源
最近更新 更多