python - 如何在 Python 中为 Postgres 自动生成 UUID?

标签 python postgresql sqlalchemy uuid

我正在尝试在 Postgres 数据库中创建对象。

我正在使用这种方法 https://websauna.org/docs/narrative/modelling/models.html#uuid-primary-keys

class Role(Base):
    __tablename__ = 'role'

    # Pass `binary=False` to fallback to CHAR instead of BINARY
    id = sa.Column(UUIDType(binary=False), primary_key=True)

但是当我创建对象时

user_role = Role(name='User')
db.session.add(user_role)
db.session.commit()

我有以下错误:

sqlalchemy.exc.IntegrityError: (psycopg2.IntegrityError) null value in column "id" violates not-null constraint

看来我没有提供任何 ID。那么,如何让数据库自动生成或自行生成呢?

最佳答案

您似乎在使用 this code .它缺少该列的默认值。您正在模拟此 SQL:

id UUID PRIMARY KEY DEFAULT uuid_generate_v4()

但你已经linked to the correct code .

id = Column(UUID(as_uuid=True),
    primary_key=True,
    server_default=sqlalchemy.text("uuid_generate_v4()"),)

或者,如果您不想加载 Postgres UUID 扩展,您可以在 Python 中创建 UUID。

from uuid import uuid4

id = Column(UUID(as_uuid=True),
    primary_key=True,
    default=uuid4,)

关于python - 如何在 Python 中为 Postgres 自动生成 UUID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52067058/

相关文章:

python - pytorch - torch.gather 的倒数

python - 由 Gluon-TS 示例生成的预测约为 0

python - 编写一个函数,反向返回一个data.txt

postgresql - 在 postgresql 中插入新行时触发更新表列?

python - 使用不同的ID字符串通过filter和filter_by获取相同的实例

c++ - 使用 Py++ 生成的代码作为 Python 扩展

python - 使用 SQL 和 python 将时间单位添加到时间戳

postgresql - 从 Postgres 备份数据库

python - 重新使用 sqlalchemy ORM 对象插入多条记录

python - 如何在 SQLAlchemy 中执行此递归公用表表达式?