Django的聚合(总和错误 [英] Django aggregate(sum error
本文介绍了Django的聚合(总和错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在使用pk过滤对象之后,我试图对一个完整的字段求和.
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)
然后,我使用了一个额外的过滤器,该过滤器在我的HTML中是减
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>
这是 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'
推荐答案
如果对空查询集求和,则求和结果为 无
.然后,在以后的视图中,您从整数中减去 None
,但是Python无法从整数中减去 None
,因此出现了错误.
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.
您可以使用或0
在您的视图中将 None
替换为零:
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
这篇关于Django的聚合(总和错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文