문제

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?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top