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

FastAPI+PostgreSQL开发时SQLAlchemy报created_at列不存在错误求助

问题解决:FastAPI + PostgreSQL 中 created_at 字段不存在错误

错误根源

你在SQLAlchemy模型中定义了created_at字段,但数据库的posts表并未同步创建该列——大概率是先创建了表,之后才添加的created_at字段,未更新数据库结构。

解决方案

1. 同步数据库表结构

生产/规范方案:使用Alembic迁移(推荐)

这是管理数据库结构变更的标准方式,不会丢失现有数据:

  • 初始化迁移环境:
    alembic init alembic
    
  • 编辑alembic.ini,配置你的PostgreSQL数据库URL:
    sqlalchemy.url = postgresql://username:password@localhost/dbname
    
  • 修改alembic/env.py,将target_metadata指向你的SQLAlchemy Base模型的元数据:
    # 导入你的Base模型
    from app.models import Base
    target_metadata = Base.metadata
    
  • 生成迁移脚本:
    alembic revision --autogenerate -m "add created_at column to posts"
    
  • 执行迁移,更新数据库:
    alembic upgrade head
    

开发环境快速方案:重建表(会丢失数据)

仅在开发测试时使用,删除现有表后让SQLAlchemy重新创建:
在你的数据库初始化代码中添加:

from sqlalchemy import create_engine
from app.models import Base

engine = create_engine("postgresql://username:password@localhost/dbname")
# 先删除所有表
Base.metadata.drop_all(bind=engine)
# 重新创建表
Base.metadata.create_all(bind=engine)

运行一次后,记得注释掉drop_all代码,避免每次启动都清空数据。

2. 优化Pydantic模型(可选,用于响应返回)

你的请求模型(Pydantic的Post)不需要包含created_at,因为该字段由数据库自动生成。如果需要在接口响应中返回created_at,建议创建单独的响应模型:

from pydantic import BaseModel
from datetime import datetime

# 请求模型(接收前端数据)
class Post(BaseModel):
    title : str
    content : str
    published : bool = True

# 响应模型(返回给前端的数据)
class PostResponse(BaseModel):
    id: int
    title: str
    content: str
    published: bool
    created_at: datetime

    class Config:
        from_attributes = True

然后修改接口,指定响应模型:

@app.post("/posts", status_code=status.HTTP_201_CREATED, response_model=PostResponse)
def create_posts(post : Post, db : Session = Depends(get_db)):
    new_post = models.Post(**post.model_dump())
    db.add(new_post)
    db.commit()
    db.refresh(new_post)
    return new_post

3. 验证修复

重新启动FastAPI应用,用Postman发送POST请求,此时不会再出现字段不存在的错误,响应会包含数据库自动生成的created_at时间值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 03:35:13