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

如何用SQLAlchemy模型表示含GENERATED ALWAYS AS IDENTITY的PostgreSQL表?

PostgreSQL IDENTITY 列转 SQLAlchemy 模型解决方案

针对你提供的PostgreSQL表结构,要让SQLAlchemy生成GENERATED ALWAYS AS IDENTITY而非SERIAL,需要使用SQLAlchemy的Identity类型定义x_id列:

完整模型代码

from sqlalchemy import Column, Integer, Text, Identity
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class X(Base):
    __tablename__ = "x"
    x_id = Column(Integer, Identity(always=True), primary_key=True)
    x_name = Column(Text, unique=True)

关键说明

  • Identity(always=True) 直接对应PostgreSQL中的GENERATED ALWAYS AS IDENTITY;若需要GENERATED BY DEFAULT,可将always参数设为False。
  • 该特性要求SQLAlchemy 1.4及以上版本,请确保依赖版本符合要求。
  • 按此定义后,SQLAlchemy生成的建表语句会完全匹配原PostgreSQL表的IDENTITY列规则,不会使用旧的SERIAL类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 17:50:32