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

FastAPI+SQLModel Todo接口返回空数组及TypeError问题求助

问题排查与修复方案

一、访问/{id}/路径抛出TypeError: Boolean value of this clause is not defined

问题根源

repos/todo_repo.py的select_todo函数中,直接对SQLModel查询语句对象statement做布尔判断(if not statement:)。SQLAlchemy的查询ClauseElement对象不允许直接转换为布尔值,因为无法明确其逻辑真假含义,因此触发该异常。

修复代码

移除对statement的无效判断,改为执行查询后检查结果是否存在:

from models.todo import ToDo
from sqlmodel import Session, select
from database.db import engine  # 补充engine导入

def select_todo(id: int):
    with Session(engine) as session:
        statement = select(ToDo).where(ToDo.id == id)
        result = session.exec(statement)
        todo = result.first()
        # 未找到数据时可返回None或抛出404异常
        if not todo:
            return None
            # 也可以选择抛出异常:
            # from fastapi import HTTPException
            # raise HTTPException(status_code=404, detail="Todo不存在")
        return todo

二、访问根路径返回空数组(已通过SQLite浏览器添加数据)

可能原因及修复

  1. todo_repo.py未导入数据库engine
    你提供的代码中,select_all_todos函数使用Session(engine)但未导入engine,会导致连接错误数据库或运行时异常。
    修复:在todo_repo.py顶部添加导入:

    from database.db import engine
    
  2. 数据库文件路径不匹配
    代码中数据库路径为sqlite:///database.db,文件默认生成在启动服务器时的工作目录。如果SQLite浏览器打开的是其他路径下的database.db,就会出现代码读取的数据库无数据的情况。
    验证:查看服务器启动时的SQL日志(echo=True已开启日志),确认连接的数据库文件路径,再用SQLite浏览器打开对应文件检查数据。

  3. Session使用不规范
    确保每次查询使用独立Session,你的select_all_todos函数用with Session(engine) as session:的写法是正确的,避免直接使用database.db中定义的全局session对象。

修正后的select_all_todos函数

from models.todo import ToDo
from sqlmodel import Session, select
from database.db import engine

def select_all_todos():
    with Session(engine) as session:
        statement = select(ToDo)
        results = session.exec(statement)
        return results.all()

额外代码问题补充

  1. models/todo.py中Optional未导入,需补充:
from typing import Optional
from sqlmodel import Field, SQLModel

class ToDo(SQLModel, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    name: str
    is_done: bool = False
  1. main.py中create_db_and_tables函数被注释,若未使用Alembic迁移工具,建议在启动前创建表(注意调用顺序,uvicorn.run是阻塞函数):
def create_db_and_tables():
    SQLModel.metadata.create_all(engine)

if __name__ == '__main__':
    create_db_and_tables()
    uvicorn.run("main:app", host='localhost', port=8000, reload=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 13:05:26