30

All of my tables defined in SQLAlchemy have an id column of type UUID.

from sqlalchemy.ext.declarative import declarative_base
from uuid import uuid4
Base = declarative_base()

class MyTable(Base):
    id = Column(UUIDtype, default=uuid4, primary_key=True)

Where UUIDtype is a special column type for the PostgreSQL UUID type. This successfully creates the UUID column in PostgreSQL, but only generates a default UUID value when inserting using SQLAlchemy. This is fine for some of my use cases, but I want to assign the column's default on the PostgreSQL side of things in case an insert occurs outside of SQLAlchemy.

The following SQL command places the proper default on the column:

ALTER TABLE my_table ALTER COLUMN id SET DEFAULT uuid_generate_v4()

How can I assign this uuid_generate_v4() function as the column default through SQLAlchemy model definition? If the only option is through executing a raw SQL statement, is there a way for me to hook that statement's execution into the table creation process?

1 Answer 1

52

You should use server_default parameter for this.

id = Column(UUIDtype, server_default=text("uuid_generate_v4()"), primary_key=True)

See Server Side Defaults for more information.

Sign up to request clarification or add additional context in comments.

3 Comments

Install uuid-ossp module with create extension uuid-ossp
Or use gen_random_uuid() instead of uuid_generate_v4() and install pgcrypto with create extension pgcrypto
gen_random_uuid() is now part of PostgreSQL native as of version 13, and so doesn't require a module. postgresql.org/docs/13/functions-uuid.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.