How to autogenerate UUID for Postgres in Python?

Viewed 15810

I'm trying to create objects in Postgres db.

I'm using this approach 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)

But when I create object

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

I have the following error:

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

Looks like I didn't provide any ID. So, how I can make the database auto-generate it or generate on my own?

4 Answers

You appear to be using this code. It's missing a default for the column. You're emulating this SQL:

id UUID PRIMARY KEY DEFAULT uuid_generate_v4()

But you've already linked to the correct code.

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

Alternatively if you don't want to load a Postgres UUID extension, you can create the UUIDs in Python.

from uuid import uuid4

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

You could use the uuid module and just set a column default. For example:

from uuid import uuid4
from sqlalchemy import Column, String

class Role(Base):
    __tablename__ = 'role'

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

What I actually came to is:

import uuid

class SomeClass(db.Model):
    __tablename__ = 'someclass'

    id = db.Column(UUID(as_uuid=True),
        primary_key=True, default=lambda: uuid.uuid4().hex)
import uuid

myId = uuid.uuid4()
print(myId)
Related