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

FastAPI返回Project对象遇JSON序列化错误,求解决方案

修复 TypeError: Object of type Project is not JSON serializable 错误

1. 确认接口返回执行后的ORM实例列表,而非Query对象

检查接口代码,确保执行SQLAlchemy查询方法(如.all()),不要直接返回Query对象:

错误示例:

@app.get("/projects", response_model=list[schemas.ProjectSchema])
def get_projects(db: Session = Depends(get_db)):
    # 错误:返回了未执行的Query对象
    return db.query(models.Project)

正确示例:

@app.get("/projects", response_model=list[schemas.ProjectSchema])
def get_projects(db: Session = Depends(get_db)):
    projects = db.query(models.Project).all()  # 执行查询获取实例列表
    return projects

2. 确保Pydantic Schema配置正确

检查schemas.py中的ProjectSchema,确认:

  • 开启ORM模式(Pydantic v1用orm_mode = True,v2用from_attributes = True)
  • 字段名称、类型与SQLAlchemy模型models.Project完全匹配

Pydantic v1示例:

from pydantic import BaseModel

class ProjectSchema(BaseModel):
    id: int
    name: str
    # 其他对应字段...

    class Config:
        orm_mode = True

Pydantic v2示例:

from pydantic import BaseModel

class ProjectSchema(BaseModel):
    id: int
    name: str
    # 其他对应字段...

    model_config = {"from_attributes": True}

若字段名不匹配(如ORM模型用project_name而Schema用name),需修改字段名或添加别名保持一致。

3. 手动转换ORM实例为Pydantic模型(兜底方案)

如果自动序列化失效,可手动转换后返回:

@app.get("/projects", response_model=list[schemas.ProjectSchema])
def get_projects(db: Session = Depends(get_db)):
    projects = db.query(models.Project).all()
    # 逐个转换为Schema对象
    return [schemas.ProjectSchema.from_orm(project) for project in projects]

4. 处理未序列化的关联字段

若Project模型包含关联关系(如外键关联其他模型),需对应处理:

  • 要么在Schema中排除关联字段
  • 要么为关联模型创建对应Schema并引用

排除关联字段示例:

class ProjectSchema(BaseModel):
    id: int
    name: str

    class Config:
        orm_mode = True
        exclude = ["tasks"]  # 排除关联的tasks字段

引用关联模型Schema示例:

class TaskSchema(BaseModel):
    id: int
    content: str
    class Config:
        orm_mode = True

class ProjectSchema(BaseModel):
    id: int
    name: str
    tasks: list[TaskSchema]  # 引用关联模型的Schema
    class Config:
        orm_mode = True

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 01:37:10