【发布时间】:2014-12-24 06:09:22
【问题描述】:
我正在使用SQLAlchemy 连接到 postgresql 数据库。我在 postgresql 中将我的主键列定义为 serial 类型,即自动增量整数,并在我的 SQLAlchemy 模型中用 primary_key=true 标记它们。
在提交SQLAlchemy 会话时,模型被保存到数据库中,我可以看到数据库中设置的主键,但我的SQLAlchemy 模型对象上的id 属性始终具有None 的值即它没有获取自动增量值。我不确定我做错了什么。
我检查了现有的 SO 问题,但没有找到答案:
- Set SQLAlchemy to use PostgreSQL SERIAL for identity generation
- sqlalchemy flush() and get inserted id?
我的代码如下:
在 postgres 中创建表:
CREATE TABLE my_model
(
id serial NOT NULL,
type text,
user_id integer,
CONSTRAINT pk_network_task PRIMARY KEY (id)
)
WITH (
OIDS=FALSE
);
设置 SQLAlchemy 和模型:
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
engine = create_engine(db_url, convert_unicode=True, echo=True)
session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine))
class MyModel(Base):
__tablename__ = 'my_model'
id = sa.Column(sa.Integer, primary_key=True)
user_id = sa.Column(sa.Integer)
type = sa.Column(sa.String)
尝试并存储模型:
my_model = MyModel()
user_id = 1
type = "A type"
session.merge(my_model)
session.commit()
my_model.id #Always None, don't know why
my_model.id 在提交之后仍然是None。我也尝试在会话中调用close,但这也不起作用。
【问题讨论】:
标签: python postgresql sqlalchemy