我的Discount
模型描述了系统中所有折扣类型的通用字段。我有一些代理模型,它们描述了计算总数的具体算法。基Discount
类具有一个名为的成员字段type
,该成员字段是一个字符串,用于标识其类型及其相关类。
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没有类型。如何解决此问题,或者还有其他方法可以解决此问题?
您的init方法需要看起来像这样:
def __init__(self, *args, **kwargs):
super(Discount, self).__init__(*args, **kwargs)
if self.type:
self.__class__ = getattr(sys.modules[__name__], self.type + 'Discount')
您需要先致电super的,__init__
然后才能访问self.type
。
请谨慎调用字段,type
因为type
它也是python内置函数,尽管您可能不会遇到任何问题。
请参阅:http :
//docs.python.org/library/functions.html#type