Django多态性破解

时间:2011-04-10 23:10:35

标签: python django inheritance django-models

我正试图在Django中烘焙出一种“单表继承”a.k.a.“每个层次结构表”模型。

这是我想做的事情:

class PolymorphicModel(models.Model):

   content_type = models.ForeignKey(ContentType)

   class Meta:
       abstract = True

   def __init__(self, *args, **kwargs):
       super(PolymorphicModel, self).__init__(*args, **kwargs)
       # Dynamically switch the class to the actual one
       self.__class__ = self.content_type.model_class()

   def save(self, *args, **kwargs):
       if not self.content_type:
           # Save the actual class name for the future.
           self.content_type = ContentType.objects.get_for_model(self.__class__)
           super(PolymorphicModel, self).save(*args, **kwargs)

然后是实际的层次结构:

class Base(PolymorphicModel):

    a = models.IntegerField()
    b = models.IntegerField()

    @abstractmethod
    def something(self): pass


class DerivedA(Base):

    def something(self):
        return self.a


class DerivedB(Base):

    def something(self):
        return self.b

很遗憾,在构建DoesNotExist时出现错误DerivedA()。它抱怨content_type不存在。

修改

关于我的问题:

  • 为什么我会得到例外,如何解决?

请参阅下面的答案:content_type显然不是一个可行的名称。

  • 我试图通过这种方式实现的目标是什么?

是的!而且效果很好。也可以使用类名而不是内容类型。这具有适当处理proxy = True的附加值。

1 个答案:

答案 0 :(得分:1)

显然,content_type是一个保留名称。我将属性名称更改为ct,现在可以正常工作。

我在这里通过解决方案发表: http://djangosnippets.org/snippets/2408/

相关问题