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

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

问题描述

是否可以将列(主键)定义为 UUID 如果使用 PostgreSQL,则href ="http://www.sqlalchemy.org/" rel ="noreferrer"> SQLAlchemy (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(db.Integer, primary_key=True)
    id = db.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4, unique=True, nullable=False)

请注意不要错过将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天全站免登陆