How can I use UUIDs in SQLAlchemy?

后端 未结 8 991
心在旅途
心在旅途 2020-12-07 10:58

Is there a way to define a column (primary key) as a UUID in SQLAlchemy if using PostgreSQL (Postgres)?

8条回答
  •  抹茶落季
    2020-12-07 11:40

    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(db.Integer, primary_key=True)
        id = db.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4, unique=True, nullable=False)
    

    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.

提交回复
热议问题