<p>这是因为您为它提供了一个显式的<code>Sequence</code>。postgresql中的<code>SERIAL</code>数据类型生成它自己的<em>序列,SQLAlchemy知道如何定位该序列-因此,如果省略<code>Sequence</code>,SQLAlchemy将呈现<code>SERIAL</code>,假设意图是列是自动递增的(由<code>autoincrement</code>参数和整数主关键字共同决定;它默认为True)。但是当<code>Sequence</code>被传递时,SQLAlchemy看到的意图是您不希望由<code>SERIAL</code>隐式创建序列,而是您指定的序列:</p>
<pre><code>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)
</code></pre>
<p>输出:</p>
<pre><code>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)
)
</code></pre>