【问题标题】:Django polymorphism hackDjango 多态性破解
【发布时间】:2011-08-02 16:30:57
【问题描述】:

我正在尝试在 Django 中烘焙一种“单表继承”,也就是“每个层次结构的表”模型。

这是我想做的:

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

不幸的是,我在构造 DerivedA() 时收到错误 DoesNotExist。它抱怨content_type 不存在。

编辑:

关于我的问题:

  • 为什么会出现异常,如何解决?

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

  • 我试图通过这种方式实现的目标是否可行?

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

【问题讨论】:

    标签: python django inheritance django-models


    【解决方案1】:

    Ups,显然content_type 是一个保留名称。我将属性名称更改为ct,现在可以使用了。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-20
      • 2011-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-19
      相关资源
      最近更新 更多