我有这样的模型:
class Category(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=128)
budget = models.DecimalField(default=0.0, decimal_places=2, max_digits=8, help_text="Amount in dollars ($)")
class Task(models.Model):
description = models.CharField(max_length=128)
owner = models.ForeignKey(User, default="bride")
category = models.ForeignKey(Category)
cost = models.DecimalField(default=0.0, decimal_places=2, max_digits=6, help_text="Amount in dollars ($)")
我想找到每个类别的所有预算的总和并显示remaining budget
:
categories = Category.objects.filter(user_id=request.user.id).order_by("name")
categories_cost = [Task.objects.filter(category=i).aggregate(Sum('cost')) for i in categories]
category_budget = [i.budget for i in categories]
categories = zip(categories, remaining_budget)
有些类别可能还没有任务。因此,categories_cost
看起来像这样:
[{'cost__sum': None}, {'cost__sum': Decimal('0.00')}, {'cost__sum': None}, {'cost__sum': Decimal('300.00')}]
因此,当我尝试减去时,会出现此错误:
>>> remaining_budget = [i.budget - j['cost__sum'] for i, j in zip(categories, rem)]
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'Decimal' and 'NoneType'
如何解决这个问题?