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

调用get_n_Antiprotozoal_for_PCT触发int()参数为NoneType报错如何解决

问题原因
  • 触发TypeError的直接原因:当传入的pct值没有匹配到任何符合条件的PrescribingData记录时,func.sum()会返回NULL,对应Python里的None,直接把None传给int()就会触发类型错误。
  • 现有代码的隐藏问题:你在聚合查询后加limit(n)完全无效,sum是聚合函数,返回结果本身只有1行,limit不会生效。如果你的业务需求是限制参与求和的行数,需要把limit放在过滤后的子查询中。
修复方案

推荐调整查询逻辑,从SQL层面处理空值同时修正limit的生效范围,修改后的代码如下:

from sqlalchemy import func

def get_n_Antiprotozoal_for_PCT(self, pct, n):
    """Return sum of antiprotozoal items for a given PCT, limited to n rows."""
    # 先过滤符合条件的行,限制行数后再求和
    subquery = db.session.query(PrescribingData.items)\
        .filter(
            PrescribingData.BNF_code.startswith('0504'),
            PrescribingData.PCT == pct
        ).limit(n).subquery()
    # 用coalesce把sum为空的情况默认转成0,避免返回None
    sum_val = db.session.query(func.coalesce(func.sum(subquery.c.items), 0)).scalar()
    return int(sum_val)

如果不需要调整limit的逻辑,只想快速修复空值报错,也可以直接在Python层加空值判断:

def get_n_Antiprotozoal_for_PCT(self, pct,n):
    """Return all the data for a given PCT."""
    res = db.session.query(func.sum(PrescribingData.items).filter(PrescribingData.BNF_code.startswith('0504'),PrescribingData.PCT == pct)).limit(n).first()[0]
    return int(res) if res is not None else 0

内容的提问来源于stack exchange,提问作者Maddie Zhang

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 13:54:03