You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django聚合Sum报错:int与NoneType无法执行减法运算

Fixing the TypeError: unsupported operand type(s) for -: 'int' and '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.


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.

  1. First, import the required functions:
from django.db.models import Sum
from django.db.models.functions import Coalesce
  1. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:22:18