如何在 SQLAlchemy 中使用 UUID? [英] How can I use UUIDs in SQLAlchemy?

查看:33
本文介绍了如何在 SQLAlchemy 中使用 UUID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将列(主键)定义为 UUIDSQLAlchemy 如果使用 PostgreSQL(Postgres)?

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

推荐答案

sqlalchemy postgres 方言支持 UUID 列.这很简单(问题特别是 postgres)——我不明白为什么其他答案都这么复杂.

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.

这是一个例子:

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)

注意不要错过将 callable uuid.uuid4 传递到列定义中,而不是使用 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:

表示此列默认值的标量、Python 可调用或 ColumnElement 表达式,如果在插入的 VALUES 子句中未指定此列,则将在插入时调用该表达式.

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.

这篇关于如何在 SQLAlchemy 中使用 UUID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆