Django:模型继承:FK & M2M

标签 django inheritance django-models data-modeling

我想这么做: 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 的关系

请告知....如果您有任何问题或不理解我正在解释的内容,也请告诉我。我使用的文件非常复杂,所以我不想发布整个文件,因为我知道它会破坏这种关系。

最佳答案

您不能与抽象模型建立关系,但这是您尝试做的事情(ManyToManyFieldOtherModel)。如果你想完成这项工作,你需要从 OtherModel 中删除 abstract = True 并将 common 添加到你的 INSTALLED_APPS !

如果你想从 Base 的子类关联到 OtherModel 的不同子类,你需要在子类上定义关系,而不是在抽象模型上!

关于Django:模型继承:FK & M2M,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3955875/

相关文章:

django - 覆盖 Django 模型中的深度复制

python - 如何在 Django 中创建一个分为两部分的注册表单,以便一次调用仅在电子邮件验证后才填写第二部分?

python - 安装 djangocms-blog 后出现导入错误 : cannot import name 'python_2_unicode_compatible' from 'django.utils .encoding'

sql - 引用 URL 中的对象 - 您使用主键还是最佳实践是什么?

python - url django 中渲染的 slugs 不正确

C#静态接口(interface)或抽象实现

django - 如何使用模板标签从 django 模板中的数据库呈现 html 文本

javascript - Flot 未在 Django 中渲染

Scala: 'type A = XXX' 和 'final type A = XX' 之间的区别?

c# - 继承调用错误的 Equals() 方法