Join the Stack Overflow Community
Stack Overflow is a community of 6.8 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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?

share|improve this question
up vote 13 down vote accepted

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.

share|improve this answer
    
Thank you. That's exactly what I needed. – Tanner Semerad Dec 12 '13 at 20:41
    
Install uuid-ossp module with create extension uuid-ossp – mozillazg Jan 28 '16 at 6:51
    
Or use gen_random_uuid() instead of uuid_generate_v4() and install pgcrypto with create extension pgcrypto – mozillazg Jan 28 '16 at 6:52

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.