作者:帝薩克斯_271 | 来源:互联网 | 2023-05-26 15:31
我正在尝试建立一个Django模型,作为其他模型的基类.Base模型有两个ForeignKey字段到同一个类的其他对象(TestForeign).我可以使用多表继承来使模型工作,但我想使用抽象模型继承,因为我已经读过使用多元继承时存在一些性能问题.
以下示例在我使用多表继承(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> knbk..:
使用%(class)s
和%(app_label)s
您的相关名称,如文档中所指定.
EG:foo = models.ForeignKey(TestForeign,related_name =“%(app_label)s _%(class)s_foo”)