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

FastAPI+Tortoise创建实体时,created_at字段不存在报错排查

问题描述

我正在开发一个基于FastAPI和Tortoise的Python应用,模型代码如下:

class Companies(Model):
    id = fields.UUIDField(pk=True)
    name = fields.CharField(max_length=20)
    location = fields.CharField(max_length=100)
    created_at = fields.DatetimeField(auto_now_add=True)
    updated_at = fields.DatetimeField(auto_now=True)

companies_pydentic= pydantic_model_creator(Companies, name="Companies")
companies_pydenticIn= pydantic_model_creator(Companies, name="CompaniesIn", exclude_readonly=True)

对应的创建公司接口代码:

@router.post('/')
async def create_companies(company_info: companies_pydenticIn):
    print(company_info)
    company_obj = await Companies.create(**company_info.dict(exclude_unset=True))
    print(company_obj)
    response = await companies_pydentic.from_tortoise_orm(company_obj)
    return {"status": "ok", "data" : response}

最初遇到422未处理实体错误,提示需传入created_at和updated_at字段,通过生成排除只读字段的Pydantic模型解决了该问题。但现在出现Tortoise错误:

tortoise.exceptions.OperationalError: column "created_at" of relation "companies" does not exist
解决方案

这个错误的核心原因是:数据库companies表中不存在created_at和updated_at字段——虽然Tortoise模型里定义了这两个字段,但数据库表结构没有同步更新。

解决步骤如下:

  • 执行数据库迁移同步表结构
    Tortoise ORM需要通过迁移工具同步模型定义到数据库,推荐使用官方配套的aerich工具:

    1. 安装aerich:
      pip install aerich
      
    2. 初始化aerich(替换your_config_module.TORTOISE_ORM为你项目中的Tortoise配置路径):
      aerich init -t your_config_module.TORTOISE_ORM
      
    3. 初始化迁移目录:
      aerich init-db
      
    4. 生成迁移文件:
      aerich migrate --name add_created_updated_columns
      
    5. 应用迁移到数据库:
      aerich upgrade
      
  • 如果手动管理表结构
    若你是手动创建的数据库表,需要手动添加这两个字段:

    • 对PostgreSQL:
      ALTER TABLE companies 
      ADD COLUMN created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
      ADD COLUMN updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP;
      
    • 对MySQL:
      ALTER TABLE companies 
      ADD COLUMN created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
      ADD COLUMN updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;
      

完成以上操作后,重新调用接口即可解决该错误。

内容的提问来源于stack exchange,提问作者Karim El Nino

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 05:55:11