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

如何用SQLAlchemy创建PostgreSQL的GENERATED ALWAYS AS IDENTITY主键

使用SQLAlchemy创建PostgreSQL的tbl表模型

核心模型定义

针对你提供的PostgreSQL DDL,对应的SQLAlchemy Declarative模型可以这样写:

from sqlalchemy import Column, Integer, Identity
from sqlalchemy.orm import declarative_base

Base = declarative_base()

class Tbl(Base):
    __tablename__ = 'tbl'
    
    tbl_id = Column(Integer, Identity(always=True), primary_key=True)
    tbl_x = Column(Integer)

关键说明

  • __tablename__ = 'tbl' 指定模型映射的数据库表名,与DDL中的表名完全一致。
  • tbl_id 列通过 Identity(always=True) 明确对应PostgreSQL的GENERATED ALWAYS AS IDENTITY约束,确保该列的值由数据库自动生成,且无法手动指定(除非使用OVERRIDING SYSTEM VALUE语法)。
  • primary_key=True 标记该列为表的主键,匹配DDL中的定义。

创建数据表

完成模型定义后,通过以下代码连接数据库并创建表:

from sqlalchemy import create_engine

# 替换为你的PostgreSQL连接字符串,格式为 postgresql://用户名:密码@主机:端口/数据库名
engine = create_engine("postgresql://user:password@localhost:5432/dbname")

# 创建所有定义的模型对应的表(仅当表不存在时执行创建)
Base.metadata.create_all(engine)

执行以上代码后,PostgreSQL中会生成结构与你提供的DDL完全一致的tbl表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 23:53:13