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

时间:2018-08-28 22:33:52

标签: python postgresql sqlalchemy uuid

我正在尝试在Postgres db中创建对象。

我正在使用这种方法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。那么,如何使数据库自动生成或自行生成?

4 个答案:

答案 0 :(得分:5)

您似乎正在使用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,)

答案 1 :(得分:2)

您可以使用uuid模块,并将其设置为默认列。例如:

from uuid import uuid4
from sqlalchemy import Column, String

class Role(Base):
    __tablename__ = 'role'

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

答案 2 :(得分:2)

我真正想到的是:

try {
    restTemplate.exchange(...); // do your request (can use get, post, etc..)
} catch (HttpClientErrorException e) {
    log.info("OH NO! IT'S AN ERROR FROM THE CLIENT: {}", e.getResponseBodyAsString());
} catch (HttpServerErrorException e) {
    log.info("OH NO! IT'S AN ERROR FROM THE SERVER: {}", e.getResponseBodyAsString());
}

答案 3 :(得分:-1)

import uuid

myId = uuid.uuid4()
print(myId)