0

我有这样的模型:

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'

如何解决这个问题?

4

1 回答 1

0

有很多解决方案。这是最简单的:

remaining_budget = [i.budget - (j['cost__sum'] or 0) for i, j in zip(categories, rem)]

或使用地图:

rem = map(lambda x: (x or 0), rem)

或使用过滤器:

def no_nones(item):
    if item is None:
        return 0
    return item

rem = filter(no_nones, rem)
于 2013-10-06T11:20:02.580 回答