在生成器中访问Python类@property

时间:2016-01-14 10:29:02

标签: python django django-models

这是我的CurrencyLot类:

class CurrencyLot(models.Model):
    _amount = models.IntegerField(default=0)
    expiry_date = models.DateTimeField(null=True, blank=True)
    creation_date = models.DateTimeField(auto_now_add=True)
    is_expired = models.BooleanField(default=False)
    _usage_count = models.IntegerField(default=1)

    class Meta:
        ordering = ['expiry_date',]

    @property
    def amount(self):
        if self._usage_count < 1 or self.is_expired:
            return 0
        else:
            return self._amount

    @property
    def usage_count(self):
        return self._usage_count

    def set_amount(self, amount):
        self._amount = amount
        self.save()
        return self._amount

我的金额为&#39;私人&#39;变量,并使用@property来访问它。 这个函数抛出错误:

def deduct_amount(self, deduction):
        deduction = int(deduction)
        currency_lots_iterator = self.currency_lots.filter(is_expired=False).iterator()
        while deduction > 0:
            if deduction > currency_lots_iterator.amount:
                deduction -= currency_lots_iterator.amount
                currency_lots_iterator.set_amount(0)
                currency_lots_iterator.next()
            elif deduction == currency_lots_iterator.amount:
                deduction = 0
                currency_lots_iterator.set_amount(0)
            elif deduction < currency_lots_iterator.amount:
                deduction = 0
                currency_lots_iterator.set_amount(currency_lots_iterator.amount-deduction)
        return self.total_valid_amount()

错误是:AttributeError:&#39; generator&#39;对象没有属性&#39; amount&#39;。

有没有办法做到这一点?

1 个答案:

答案 0 :(得分:2)

您的currency_lots_iterator是一个生成器(迭代来自QuerySet的对象) - 您必须从中获取下一个项目并从中访问金额:

currency_lots_iterator = self.currency_lots.filter(is_expired=False).iterator()
while deduction > 0:
    currency_lot = currency_lots_iterator.next()

然后使用currency_lot.amountcurrency_lot.set_amount(x)