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

使用FastAPI与SQLAlchemy创建新增文章函数时遇异常求助

问题分析与解决方案

你的错误根源有两个核心问题:

  • 混淆了SQLAlchemy数据库模型与FastAPI依赖的Pydantic模型:FastAPI需要用Pydantic模型处理请求体解析和响应序列化,而你直接把SQLAlchemy的Post类用作请求参数,还尝试返回SQLAlchemy实例——这类数据库模型不具备自动序列化能力。
  • 创建数据库实例时字段名错误:models.Post的字段是title,你写成了titles,这会导致后续数据库操作失败。

第一步:创建Pydantic模型

新建schemas.py文件,定义用于请求和响应的数据模型:

from pydantic import BaseModel
from datetime import datetime

# 用于接收创建文章的请求体
class PostCreate(BaseModel):
    title: str
    content: str
    published: bool = True  # 与数据库默认值保持一致

# 用于格式化响应数据(可选,可精准控制返回字段)
class PostResponse(BaseModel):
    id: int
    title: str
    content: str
    published: bool
    created_at: datetime

    class Config:
        orm_mode = True  # 允许直接从SQLAlchemy实例解析数据

第二步:修正main.py代码

from fastapi import FastAPI, Depends
from sqlalchemy.orm import Session
from database import engine, get_db
import models
from schemas import PostCreate, PostResponse  # 导入Pydantic模型

models.Base.metadata.create_all(bind=engine)

app = FastAPI()

@app.post('/posts', response_model=PostResponse)
def create_posts(post: PostCreate, db: Session = Depends(get_db)):
    # 修正字段名错误,添加数据库会话操作
    new_post = models.Post(title=post.title, content=post.content, published=post.published)
    db.add(new_post)
    db.commit()
    db.refresh(new_post)  # 刷新实例,获取数据库自动生成的id、created_at等字段
    return new_post

若坚持使用response_model=None的处理方式

如果不想用Pydantic响应模型,需手动将SQLAlchemy实例转为字典后返回:

@app.post('/posts', response_model=None)
def create_posts(post: PostCreate, db: Session = Depends(get_db)):
    new_post = models.Post(title=post.title, content=post.content, published=post.published)
    db.add(new_post)
    db.commit()
    db.refresh(new_post)
    return {'data': {
        'id': new_post.id,
        'title': new_post.title,
        'content': new_post.content,
        'published': new_post.published,
        'created_at': new_post.created_at.isoformat()
    }}

注:之前设置response_model=None无效,是因为FastAPI仍会尝试序列化你返回的SQLAlchemy实例,而这类实例无法被默认序列化器处理,必须转为字典或用Pydantic模型包装。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 22:37:47