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?
PostgreSQL supports sequences, and SQLAlchemy uses these as the default means of creating new primary key values for integer-based primary key columns.
The psycopg2 is over 2x faster than SQLAlchemy on small table. This behavior is expected as psycopg2 is a database driver for postgresql while SQLAlchemy is general ORM library.
A generic function is a pre-established Function class that is instantiated automatically when called by name from the func attribute. Note that calling any name from func has the effect that a new Function instance is created automatically, given that name.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With