在 Django 中使用抽象多重继承时外键冲突

ForeignKeys clashing when using abstract multiple inheritance in Django

我正在尝试建立一个 Django 模型作为其他模型的基础 class。 Base 模型有两个 ForeignKey 字段指向相同 class (TestForeign) 的其他对象。我可以使用多表继承让模型工作,但我想使用抽象模型继承,因为我读过有一些 performance issues when using multitable inheritance.

以下示例在我使用多表继承 (abstract = False) 时有效,但在我 运行 使用抽象继承时失败。

class TestForeign(models.Model):
  test = models.CharField(max_length=100)

class BaseModel(models.Model):
  # specified related_name to avoid reverse accesor clash
  foo = models.ForeignKey(TestForeign, related_name='fooooo')
  bar = models.ForeignKey(TestForeign)

  class Meta:
    abstract = True

class AnotherModel(BaseModel):
  bla = models.CharField(max_length=100)

class YetAnotherModel(BaseModel):
  bla = models.CharField(max_length=100)

当我同步数据库时出现以下错误:

ERRORS:
Base.AnotherModel.bar: (fields.E304) Reverse accessor for 'AnotherModel.bar' clashes with reverse accessor for 'YetAnotherModel.bar'.
HINT: Add or change a related_name argument to the definition for 'AnotherModel.bar' or 'YetAnotherModel.bar'.
Base.AnotherModel.bar: (fields.E305) Reverse query name for 'AnotherModel.bar' clashes with reverse query name for 'YetAnotherModel.bar'.
HINT: Add or change a related_name argument to the definition for 'AnotherModel.bar' or 'YetAnotherModel.bar'.
Base.AnotherModel.foo: (fields.E304) Reverse accessor for 'AnotherModel.foo' clashes with reverse accessor for 'YetAnotherModel.foo'.
HINT: Add or change a related_name argument to the definition for 'AnotherModel.foo' or 'YetAnotherModel.foo'.
Base.AnotherModel.foo: (fields.E305) Reverse query name for 'AnotherModel.foo' clashes with reverse query name for 'YetAnotherModel.foo'.
HINT: Add or change a related_name argument to the definition for 'AnotherModel.foo' or 'YetAnotherModel.foo'.
Base.YetAnotherModel.bar: (fields.E304) Reverse accessor for 'YetAnotherModel.bar' clashes with reverse accessor for 'AnotherModel.bar'.
HINT: Add or change a related_name argument to the definition for 'YetAnotherModel.bar' or 'AnotherModel.bar'.
Base.YetAnotherModel.bar: (fields.E305) Reverse query name for 'YetAnotherModel.bar' clashes with reverse query name for 'AnotherModel.bar'.
HINT: Add or change a related_name argument to the definition for 'YetAnotherModel.bar' or 'AnotherModel.bar'.
Base.YetAnotherModel.foo: (fields.E304) Reverse accessor for 'YetAnotherModel.foo' clashes with reverse accessor for 'AnotherModel.foo'.
HINT: Add or change a related_name argument to the definition for 'YetAnotherModel.foo' or 'AnotherModel.foo'.
Base.YetAnotherModel.foo: (fields.E305) Reverse query name for 'YetAnotherModel.foo' clashes with reverse query name for 'AnotherModel.foo'.
HINT: Add or change a related_name argument to the definition for 'YetAnotherModel.foo' or 'AnotherModel.foo'.

有什么方法可以使基础 class 的引用不与派生模型发生冲突?

在您的相关名称中使用 %(class)s%(app_label)s,如 the docs 中指定的那样。