在Django中使用抽象多重继承时,ForeignKeys发生冲突

时间:2015-01-16 00:25:44

标签: python django inheritance django-models

我正在尝试设置一个Django模型,作为其他模型的基类。 Base模型有两个ForeignKey字段到同一个类的其他对象(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'.

有什么方法可以让基类的引用不会在派生模型中发生冲突?

1 个答案:

答案 0 :(得分:10)

the docs中指定的相关名称中使用%(class)s%(app_label)s