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

SQLAlchemy ORM是否支持BigInteger Identity列?如何实现?

在SQLAlchemy ORM中创建PostgreSQL BigInteger Identity列

疑问解答

1. 是否完全可行?

完全可行。PostgreSQL的IDENTITY支持关联BIGINT等多种整数类型,SQLAlchemy对此有内置支持,只是官方文档未单独给出该组合的示例。

2. 具体实现方式

无需创建自定义类型,直接通过BigInteger结合IDENTITY约束即可实现,两种常用写法如下:

方式一:利用Column的identity参数快速实现

from sqlalchemy import BigInteger, Column
from sqlalchemy.orm import declarative_base

Base = declarative_base()

class ExampleModel(Base):
    __tablename__ = "example_table"
    id = Column(BigInteger, identity=True, primary_key=True)
    # 其他字段定义...

方式二:显式使用Identity对象(支持更多配置项)

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

Base = declarative_base()

class ExampleModel(Base):
    __tablename__ = "example_table"
    id = Column(
        BigInteger,
        Identity(always=True, start=1, increment=1),
        primary_key=True
    )
    # 其他字段定义...

上述代码会生成对应的PostgreSQL SQL语句:

CREATE TABLE example_table (
    id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY
);

注意:该方案要求SQLAlchemy版本≥1.4,且PostgreSQL版本≥10(PostgreSQL 10及以上才支持IDENTITY语法)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 06:30:36