【问题标题】:How to set a column default to a PostgreSQL function using SQLAlchemy?如何使用 SQLAlchemy 将列默认设置为 PostgreSQL 函数?
【发布时间】:2013-12-30 05:11:56
【问题描述】:

我在 SQLAlchemy 中定义的所有表都有一个 UUID 类型的 id 列。

from sqlalchemy.ext.declarative import declarative_base
from uuid import uuid4
Base = declarative_base()

class MyTable(Base):
    id = Column(UUIDtype, default=uuid4, primary_key=True)

其中UUIDtype 是 PostgreSQL UUID 类型的特殊列类型。这成功地在 PostgreSQL 中创建了 UUID 列,但仅在使用 SQLAlchemy 插入时生成默认 UUID 值。这对于我的一些用例来说很好,但我想在 PostgreSQL 方面分配列的默认值,以防在 SQLAlchemy 之外发生插入。

以下 SQL 命令将正确的默认值放在列上:

ALTER TABLE my_table ALTER COLUMN id SET DEFAULT uuid_generate_v4()

如何通过 SQLAlchemy 模型定义将此 uuid_generate_v4() 函数指定为列默认值?如果唯一的选择是通过执行原始 SQL 语句,我有没有办法将该语句的执行挂钩到表创建过程中?

【问题讨论】:

    标签: postgresql sqlalchemy uuid


    【解决方案1】:

    您应该为此使用server_default 参数。

    id = Column(UUIDtype, server_default=text("uuid_generate_v4()"), primary_key=True)
    

    更多信息请参见Server Side Defaults

    【讨论】:

    • create extension uuid-ossp安装uuid-ossp模块
    • 或者使用gen_random_uuid()而不是uuid_generate_v4()并安装pgcryptocreate extension pgcrypto
    • gen_random_uuid() 现在是 PostgreSQL 本地版本 13 的一部分,因此不需要模块。 postgresql.org/docs/13/functions-uuid.html
    猜你喜欢
    • 1970-01-01
    • 2016-08-03
    • 2016-12-22
    • 1970-01-01
    • 2015-05-28
    • 2019-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多