Django聚合Sum报错:int与NoneType无法执行减法运算
Alright, let's break down what's causing this error and how to fix it step by step.
What's the root issue?
This error pops up because you're trying to subtract a None value from an integer. Specifically, when there are no matching ItemOut records for your filtered ItemIn object, Django's Sum aggregation function returns None instead of 0. When your template filter tries to subtract this None from selected_itemz.item_quantity (an integer), Python throws the type error.
Solution 1: Handle None in the View (Recommended)
It's best to keep logic out of templates, so let's fix the aggregation result in your views.py to ensure it always returns an integer. We'll use Django's Coalesce function to replace None with 0.
- First, import the required functions:
from django.db.models import Sum from django.db.models.functions import Coalesce
- Modify your aggregation code:
# Fetch the target ItemIn object selected_itemz = ItemIn.objects.get(pk=pk) # Use Coalesce to set sum to 0 if no ItemOut records exist item_out_total = selected_itemz.itemout_set.aggregate( total_quantity=Coalesce(Sum('item_quantity'), 0) ) # Pass the integer value to the template context = { 'selected_itemz': selected_itemz, 'item_out_quantity': item_out_total['total_quantity'] }
Now item_out_quantity will always be an integer (0 or the actual sum), so your template subtraction won't fail.
Solution 2: Handle None in the Custom Template Filter
If you prefer to fix it in the filter layer, update your subtract filter to convert None values to 0 before doing the math:
from django import template register = template.Library() @register.filter def subtract(value, arg): # Convert None values to 0 to avoid type errors val = value if value is not None else 0 arg_val = arg if arg is not None else 0 return val - arg_val
Your existing HTML usage will work without changes, since the filter now safely handles None inputs.
HTML Usage (Works for Both Solutions)
Keep your template code as is (or use it with the fixed view/filter):
{{ selected_itemz.item_quantity|subtract:item_out_quantity }}
内容的提问来源于stack exchange,提问作者Ahmed Wagdi

