【发布时间】:2012-10-12 15:40:22
【问题描述】:
我正在构建一个具有嵌套树分类的模型。词汇表Entity 继承自抽象基类TreeVocabulary。还有一个类SpecialEntity,继承自Entity。在SpecialEntity 中应该有几个额外的字段。
Entity 和 SpecialEntity 都应该是树,为此我使用 mptt http://django-mptt.github.com/django-mptt/。在Entity 中应该有一条记录,它在SpecialEntity 中有子元素(这些子元素是SpecialEntity 中的根元素)。
这就是我的想象:
class Vocabulary(models.Model):
name= models.CharField(max_length=300)
order= models.IntegerField(default=100)
class Meta:
abstract= True
class SpecialType(Vocabulary):
class TreeVocabulary(MPTTModel):
parent= TreeForeignKey('self', null=True, blank=True,
related_name='children', limit_choices_to=Q(parent__isnull=True))
class MPTTMeta:
order_insertion_by= ('name',)
class Meta:
abstract= True
class Entity(TreeVocabulary):
class SpecialEntity(Entity):
code= models.CharField(max_length=50)
type= models.ForeignKey(SpecialType)
class Meta:
ordering= ('code',)
现在,问题是由于某种原因SpecialEntity 转义 mptt:sqlall 显示一个没有parent_id 的普通表。虽然它存在于Entity,它直接继承自TreeVocabulary。
这是 django-mptt 中的错误吗?或者也许这是一个糟糕的设计? 我不是要求为我设计它,而是指出正确的方向
提前致谢!
【问题讨论】:
-
我看不到你在任何地方继承
MPTTModel。 It is necessarily -
操作,对不起,你说得对,对不起。我已根据我的更改更改了代码,但不幸的是问题仍然存在
-
是的,你说得对,对不起。我已经更改了问题中的代码,但问题仍未解决:
CREATE TABLE "vocabulary_specialentity" ( "entity_ptr_id" integer NOT NULL PRIMARY KEY REFERENCES "vocabulary_entity" ("id") DEFERRABLE INITIALLY DEFERRED, "code" varchar(50) NOT NULL, "type_id" integer NOT NULL REFERENCES "vocabulary_specialtype" ("id") DEFERRABLE INITIALLY DEFERRED ) -
您迁移表了吗?如果您对代码的更新不仅仅是一个错字修复 - 您应该将您的数据库与代码同步。
-
是的,我做了 - 没有效果。所以,现在我有继承自 MPTTModel 的 TreeVocabulary、继承自 TreeVocabulary 的实体和继承自实体的 SpecialEntity。在 Entity 中有一个完整的包(parent_id、left、right、level 等),而在 SpecialEntity 中只有 id、code 和 type_id 的外键