5

在使用 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)

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

HTML

  <br>
  <br>
  <p align="right">
  الكمية الموجودة:
       {{ selected_itemz.item_quantity|subtract:ItemOut_quantity }}
      </p>
  <br>
  <br>

这是tempaltetags文件

from django import template

register = template.Library()


@register.filter
def subtract(value, arg):
    return value - arg

现在我得到错误:

TypeError at /item/1/
unsupported operand type(s) for -: 'int' and 'NoneType'
4

1 回答 1

10

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

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

ItemOut_quantity = ItemOut_table.aggregate(sum=Sum('item_quantity'))['sum'] or 0
于 2018-05-13T12:53:34.177 回答