当前位置: 首页 > 面试题库 >

具有代理继承的Django模型多态性

白成济
2023-03-14
问题内容

我的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



 类似资料: