Search code examples
pythonpostgresqlsqlalchemyuuid

How to autogenerate UUID for Postgres in Python?


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?


Solution

  • 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,)