The sqlalchemy postgres dialect supports UUID columns. This is easy (and the question is specifically postgres) -- I don't understand why the other answers are all so complicated.
Here is an example:
from sqlalchemy.dialects.postgresql import UUID
from flask_sqlalchemy import SQLAlchemy
import uuid
db = SQLAlchemy()
class Foo(db.Model):
id = db.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
Be careful not to miss passing the callable
uuid.uuid4
into the column definition, rather than calling the function itself with uuid.uuid4()
. Otherwise, you will have the same scalar value for all instances of this class. More details here:
A scalar, Python callable, or ColumnElement expression representing the default value for this column, which will be invoked upon insert if this column is otherwise not specified in the VALUES clause of the insert.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…