Django聚合(总和错误

Ahm*_*gdi 5 python django

在使用 pk 过滤对象后,我试图对一个完整的字段求和。

视图.py

def items(request, pk):
    current_user = request.user
    selected_itemz = get_object_or_404(ItemIn, pk=pk)
    all_cats = Category.objects.all()
    cat_count = all_cats.count()
    item_count = ItemIn.objects.values_list('item_name', flat=True).distinct().count()  # returns a list of tuples..
    #all_units = Item.objects.aggregate(Sum('item_quantity'))['item_quantity__sum']
    ItemOut_table = ItemOut.objects.all().filter(item_name=selected_itemz)
    ItemOut_quantity = ItemOut_table.aggregate(Sum('item_quantity'))['item_quantity__sum']

    context = {
        #'all_units': all_units,
        'item_count': item_count,
        'cat_count': cat_count,
        'current_user': current_user,
        'ItemOut_quantity': ItemOut_quantity,
        'selected_itemz':selected_itemz,
    }

    return render(request, 'townoftech_warehouse/item_details.html', context)
Run Code Online (Sandbox Code Playgroud)

然后我使用了我subtract在 HTML 中创建的额外过滤器

HTML

  <br>
  <br>
  <p align="right">
  ?????? ????????:
       {{ selected_itemz.item_quantity|subtract:ItemOut_quantity }}
      </p>
  <br>
  <br>
Run Code Online (Sandbox Code Playgroud)

这是tempaltetags文件

from django import template

register = template.Library()


@register.filter
def subtract(value, arg):
    return value - arg
Run Code Online (Sandbox Code Playgroud)

现在我得到错误:

TypeError at /item/1/
unsupported operand type(s) for -: 'int' and 'NoneType'
Run Code Online (Sandbox Code Playgroud)

Wil*_*sem 10

如果对空查询集求和,则求和结果为None。然后在你的视图中你None从一个整数中减去它,但是 Python 无法None从一个整数中减去,因此是错误的。

您可以使用or 0,None在您的视图中替换为零:

ItemOut_quantity = ItemOut_table.aggregate(sum=Sum('item_quantity'))['sum'] or 0
Run Code Online (Sandbox Code Playgroud)