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'
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With