我收到错误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
)
答案 0 :(得分:0)
如果您要对聚合输出进行计算,因此想要将None
转换为0
并在密钥存在性方面保持健壮,则可以使用get
和or
运算符:
total_collected = ambassador.transaction.aggregate(Sum('amount')).get('amount__sum') or 0