在django中的此查询中应用条件

时间:2013-10-06 10:45:13

标签: django django-queryset django-aggregation

我有这样的模特:

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'

如何解决这个问题?

1 个答案:

答案 0 :(得分: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)