如何在Python中自动生成Postgres的UUID?

2024-04-26 21:38:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试在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)

但是当我创造物体的时候

^{pr2}$

我有以下错误:

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

看起来我没有提供任何ID。那么,我如何使数据库自动生成或自己生成?在


Tags: to方法httpsorgid数据库falsedocs
2条回答

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

id UUID PRIMARY KEY DEFAULT uuid_generate_v4()

但你已经linked to the correct code。在

^{pr2}$

或者,如果不想加载postgresuuid扩展,可以用Python创建UUID。在

from uuid import uuid4

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

您可以使用uuid模块并设置一个列默认值。例如:

from uuid import uuid4
from sqlalchemy import Column, String

class Role(Base):
    __tablename__ = 'role'

    id = Column(String, primary_key=True, default=uuid4)

相关问题 更多 >