在 Python SQL Alchemy 中创建基于字符串的序列 [英] Create a String based sequence in Python SQL Alchemy
问题描述
我正在尝试在 SQLAlchemy ORM 中创建一个基于字符串的序列.我知道最佳实践是使用基于整数的列来管理表的 ID,但在我的情况下,由于项目的某些要求,我需要将数据存储为基于字符串的 ID PK.
I'm trying to create a String based sequence in SQLAlchemy ORM. I know that the best practice is to use a Integer based column to manage ID of a table but in my case, due to some requirements of the project I need to store the data as a String based PK for ID's.
我知道在某些数据库中可以使用基于字符串的序列来存储数据,例如:
I know that in some databases it is possible to store data using a string based sequence like:
- AAA1"
- AAA2"
- AAAN"
但在 SQL 炼金术中我无法通过使用 序列 方法.它只生成基于整数的序列,我找不到在序列生成中附加"前缀的选项.
But in SQL alchemy I can't achieve this by using Sequence method. It only generates Integer based sequences and I can't find an options to "append" a prefix in the sequence generation.
有一个简单的解决方案来实现这一目标吗?
There is a easy solution to achieve this?
推荐答案
你可以在 PostgreSQL 中这样做,类似于:
You can do this in PostgreSQL similar to this:
CREATE TABLE test(
id text PRIMARY KEY,
val text
);
CREATE SEQUENCE test_id_seq OWNED BY test.id;
ALTER TABLE test
ALTER id SET DEFAULT to_hex(nextval('test_id_seq'));
在那个例子中,我使用了 to_hex
函数来获取十六进制表示,但你可以使用任何你喜欢的表达式.
In that example I used the to_hex
function to get the hexadecimal representation, but you can use any expression you like.
这篇关于在 Python SQL Alchemy 中创建基于字符串的序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!