我想这么做: http://docs.djangoproject.com/en/dev/topics/db/models/#be-careful-with-related-name
使用这种风格
这被保存为 common/abstract.py
class OtherModel(models.Model):
something = Charfield(max_length=100)
class Meta:
abstract = True
class Base(models.Model):
fk_model = models.ForeignKey(OtherModel, related_name="%(app_label)s_%(class)s_related")
class Meta:
abstract = True
然后我将它导入另一个文件。我们称这个为 app/models.py
from common.abstract import Base
class ChildB(Base):
pass
我安装了“app”但没有安装“common”。它可以在没有 FK 或 M2M 关系的情况下很好地导入,但是当我尝试添加它时,出现此错误:
/lib/python2.6/site-packages/django/db/models/fields/related.py",第 808 行,在 init assert not to.meta.abstract, "%s 无法定义与抽象类 %s 的关系"% (self.class._name__, to._meta.object_name) AssertionError: ForeignKey 无法定义与抽象类 OtherModel 的关系
请告知....如果您有任何问题或不理解我正在解释的内容,也请告诉我。我使用的文件非常复杂,所以我不想发布整个文件,因为我知道它会破坏这种关系。
最佳答案
您不能与抽象模型建立关系,但这是您尝试做的事情(ManyToManyField
到 OtherModel
)。如果你想完成这项工作,你需要从 OtherModel
中删除 abstract = True
并将 common
添加到你的 INSTALLED_APPS
!
如果你想从 Base
的子类关联到 OtherModel
的不同子类,你需要在子类上定义关系,而不是在抽象模型上!
关于Django:模型继承:FK & M2M,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3955875/