Django:-:“ NoneType”和“ NoneType”的不受支持的操作数类型

时间:2018-07-22 07:48:28

标签: django

我收到错误unsupported operand type(s) for -: 'NoneType' and 'NoneType'。原因是transaction.aggregate(Sum('amount'))reward_transaction.aggregate(Sum('amount'))尚无条目。我现在想知道是解决try / except的最佳方法,还是我没有考虑过的“更好的方法”?

views.py:

user = request.user
ambassador = user.ambassador_profile
total_collected = ambassador.transaction.aggregate(Sum('amount'))
total_redeemed = ambassador.reward_transaction.aggregate(Sum('amount'))

models.py

class Profile(models.Model):
    ambassador_reference = models.CharField(
        max_length=10,
        unique=True,
    )
    user = models.OneToOneField(
        User,
        on_delete=models.CASCADE,
        related_name='ambassador_profile',
    )
    events = models.ManyToManyField(Event)
    updated = models.DateTimeField(
        auto_now=True
    )
    created = models.DateTimeField(
        auto_now_add=True
    )

class Transaction(models.Model):
    order = models.ForeignKey(  # TODO Marc: One to One?
        Order,
        on_delete=models.PROTECT,
        related_name='transaction'
    )
    ambassador = models.ForeignKey(
        Profile,
        on_delete=models.PROTECT,
        related_name='transaction'
    )
    amount = models.PositiveIntegerField(
        verbose_name=_("Earned coins")
    )
    updated = models.DateTimeField(
        auto_now=True
    )
    created = models.DateTimeField(
        auto_now_add=True
    )

1 个答案:

答案 0 :(得分:0)

如果您要对聚合输出进行计算,因此想要将None转换为0并在密钥存在性方面保持健壮,则可以使用getor运算符:

total_collected = ambassador.transaction.aggregate(Sum('amount')).get('amount__sum') or 0