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

Python应用运行报错RuntimeError:datetime模块继承检查失败求助

Python应用RuntimeError问题分析与修复

错误信息

RuntimeError: error checking inheritance of <module 'datetime' from '/usr/local/lib/python3.9/datetime.py'> (type: module)

问题代码

import datetime
from pydantic.types import Optional
from sqlmodel import SQLModel, Field

class BlogBase(SQLModel): 
    title: str
    published_at: datetime
    # author:str = Field(default=None, foreign_key="author.id")
    body: str
    updated_at: Optional[str]

class Blog(BlogBase, table=True): 
    id: int = Field(default=True, primary_key=True)
    published_at: datetime = Field(default=datetime.utcnow(), nullable=False)


class BlogCreate(BlogBase): 
    pass

问题原因

  • 类型注解错误:直接将datetime模块当作字段类型使用,SQLModel(基于Pydantic)要求字段类型为具体的类型对象,而非整个模块。
  • Optional导入路径错误:Optional不属于pydantic.types,正确导入路径是typing或sqlmodel。
  • 默认值设置错误:datetime.utcnow()会在类定义阶段就执行,导致所有实例共享同一个初始时间,应该传入函数本身而非调用结果。
  • 主键字段配置错误:id字段的default=True不符合SQLModel主键规范,应该设为default=None以支持数据库自增逻辑。

修复方案

修正后的完整代码

from datetime import datetime
from typing import Optional
from sqlmodel import SQLModel, Field

class BlogBase(SQLModel): 
    title: str
    published_at: datetime
    # author:str = Field(default=None, foreign_key="author.id")
    body: str
    updated_at: Optional[str]

class Blog(BlogBase, table=True): 
    id: int = Field(default=None, primary_key=True)
    published_at: datetime = Field(default=datetime.utcnow, nullable=False)

class BlogCreate(BlogBase): 
    pass

关键修复点说明

  1. 导入修正:从datetime模块导入具体的datetime类型,替换原有的import datetime;同时从typing导入Optional。
  2. 类型注解修正:将published_at字段的类型从datetime(模块)改为datetime(具体类型),符合SQLModel的类型校验要求。
  3. 默认值修正:把default=datetime.utcnow()改为default=datetime.utcnow,让SQLModel在创建实例时才调用函数生成当前时间,避免时间固定。
  4. 主键配置修正:将id字段的default=True改为default=None,适配SQLModel对自增主键的默认处理逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 04:25:33