gpt4 book ai didi

python - 为什么 SQLAlchemy 不创建串行列?

转载 作者:太空狗 更新时间:2023-10-29 17:57:59 25 4
gpt4 key购买 nike

SQLAlchemy 正在为 postgresql 中的列生成但不启用序列。我怀疑我可能在引擎设置中做错了什么。

使用 SQLAlchemy 教程中的示例 (http://docs.sqlalchemy.org/en/rel_0_9/orm/tutorial.html):

#!/usr/bin/env python

from sqlalchemy import create_engine, Column, Integer, String, Sequence
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
name = Column(String(50))
fullname = Column(String(50))
password = Column(String(12))

def __repr__(self):
return "<User(name='%s', fullname='%s', password='%s')>" % (
self.name, self.fullname, self.password)

db_url = 'postgresql://localhost/serial'
engine = create_engine(db_url, echo=True)
Base.metadata.create_all(engine)

使用此脚本,生成下表:

serial=# \d+ users
Table "public.users"
Column | Type | Modifiers | Storage | Stats target | Description
----------+-----------------------+-----------+----------+--------------+-------------
id | integer | not null | plain | |
name | character varying(50) | | extended | |
fullname | character varying(50) | | extended | |
password | character varying(12) | | extended | |
Indexes:
"users_pkey" PRIMARY KEY, btree (id)
Has OIDs: no

但是,一个序列创建了:

serial=# select sequence_schema,sequence_name,data_type from information_schema.sequences ;
sequence_schema | sequence_name | data_type
-----------------+---------------+-----------
public | user_id_seq | bigint

SQLAlchemy 0.9.1、Python 2.7.5+、Postgresql 9.3.1、Ubuntu 13.10

-里斯

最佳答案

这是因为您为其提供了明确的 Sequence。 postgresql 中的 SERIAL 数据类型生成它的 own 序列,SQLAlchemy 知道如何定位 - 所以如果你省略 Sequence,SQLAlchemy 将呈现 SERIAL,假设目的是该列是自动递增的(由 autoincrement 参数与 Integer primary_key 一起确定;它默认为 True)。但是当传递 Sequence 时,SQLAlchemy 会看到您不希望 SERIAL 隐式创建的序列的意图,而是您指定的序列:

from sqlalchemy import create_engine, Column, Integer, String, Sequence
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class T1(Base):
__tablename__ = 't1'

# emits CREATE SEQUENCE + INTEGER
id = Column(Integer, Sequence('user_id_seq'), primary_key=True)

class T2(Base):
__tablename__ = 't2'

# emits SERIAL
id = Column(Integer, primary_key=True)

class T3(Base):
__tablename__ = 't3'

# emits INTEGER
id = Column(Integer, autoincrement=False, primary_key=True)

engine = create_engine("postgresql://scott:tiger@localhost/test", echo=True)
Base.metadata.create_all(engine)

输出:

CREATE SEQUENCE user_id_seq

CREATE TABLE t1 (
id INTEGER NOT NULL,
PRIMARY KEY (id)
)


CREATE TABLE t2 (
id SERIAL NOT NULL,
PRIMARY KEY (id)
)


CREATE TABLE t3 (
id INTEGER NOT NULL,
PRIMARY KEY (id)
)

关于python - 为什么 SQLAlchemy 不创建串行列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21328599/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com