Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django aggregate(sum error

Tags:

python

django

I'm trying to sum a complete field after filtering objects using pk.

Views.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)

Then I used an extra filter that I created which is subtract in my HTML

HTML

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

and here is the tempaltetags file

from django import template

register = template.Library()


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

Now I get the error :

TypeError at /item/1/
unsupported operand type(s) for -: 'int' and 'NoneType'
like image 603
Ahmed Wagdi Avatar asked May 13 '18 12:05

Ahmed Wagdi


1 Answers

If you sum over an empty queryset, then the result of the sum is None. Then later in your view you subtract that None from an integer, but Python has no way to subtract None from an integer, hence the error.

You can use or 0, to replace None with zero in your view:

ItemOut_quantity = ItemOut_table.aggregate(sum=Sum('item_quantity'))['sum'] or 0
like image 106
Willem Van Onsem Avatar answered Nov 07 '22 09:11

Willem Van Onsem