具有代理继承的 Django 模型多态性 [英] django model polymorphism with proxy inheritance
问题描述
My Discount
模型描述了系统中所有类型折扣的通用字段.我有一些代理模型,它们描述了计算总数的具体算法.基本的Discount
类有一个名为type
的成员字段,它是一个标识其类型及其相关类的字符串.
My Discount
model describes common fields for all types of discounts in the system. I have some proxy models which describe concrete algorithm for culculating total. Base Discount
class has a member field named type
, which is a string identifing its type and its related class.
class Discount(models.Model):
TYPE_CHOICES = (
('V', 'Value'),
('P', 'Percentage'),
)
name = models.CharField(max_length=32)
code = models.CharField(max_length=32)
quantity = models.PositiveIntegerField()
value = models.DecimalField(max_digits=4, decimal_places=2)
type = models.CharField(max_length=1, choices=TYPE_CHOICES)
def __unicode__(self):
return self.name
def __init__(self, *args, **kwargs):
if self.type:
self.__class__ = getattr(sys.modules[__name__], self.type + 'Discount')
super(Discount, self).__init__(*args, **kwargs)
class ValueDiscount(Discount):
class Meta:
proxy = True
def total(self, total):
return total - self.value
但我不断收到 AttributeError 异常,说 self 没有类型.如何解决这个问题,或者有其他方法可以实现吗?
But I keep getting exception of AttributeError saying self doesnt have type. How to fix this or is there another way to achieve this?
推荐答案
你的 init 方法需要看起来像这样:
Your init method needs to look like this instead:
def __init__(self, *args, **kwargs):
super(Discount, self).__init__(*args, **kwargs)
if self.type:
self.__class__ = getattr(sys.modules[__name__], self.type + 'Discount')
在访问self.type
之前,您需要调用super的__init__
.
You need to call super's __init__
before you will be able to access self.type
.
小心调用你的字段 type
因为 type
也是一个 python 内置函数,尽管你可能不会遇到任何问题.
Becareful with calling your field type
since type
is also a python built-in function, though you might not run into any problems.
参见:http://docs.python.org/library/functions.html#输入
这篇关于具有代理继承的 Django 模型多态性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!