Python Django多态性黑客
我试图在Django中烘焙出一种“单表继承”模型,也称为“每层次表”模型 以下是我想做的:Python Django多态性黑客,python,django,inheritance,django-models,Python,Django,Inheritance,Django Models,我试图在Django中烘焙出一种“单表继承”模型,也称为“每层次表”模型 以下是我想做的: class PolymorphicModel(models.Model): content_type = models.ForeignKey(ContentType) class Meta: abstract = True def __init__(self, *args, **kwargs): super(PolymorphicModel, self)
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
。它抱怨内容类型不存在
编辑:
关于我的问题:
- 为什么会出现异常,如何修复
内容类型
显然不是一个可行的名称
- 我想通过这种方式实现的目标是可行的吗
是的!而且它工作得很漂亮。也可以使用类名而不是内容类型。这有一个适当处理
proxy=True
的附加值。Ups,显然content\u type
是一个保留名称。我将属性名称更改为ct
,现在可以使用了
我在这里发布了解决方案: