如何用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
相关产品推荐
相关产品推荐

