Python 没有自动增量的sqlalchemy主键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27498991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:53:10  来源:igfitidea点击:

sqlalchemy primary key without auto-increment

pythondatabasesqlalchemy

提问by stevelle

I'm trying to establish a table with a layout approximately like the following:

我正在尝试建立一个布局大致如下的表格:

class Widget(db.Model):
    __tablename__ = 'widgets'
    ext_id = db.Column(db.Integer, primary_key=True)
    w_code = db.Column(db.String(34), unique=True)
    # other traits follow...

All field values are provided through an external system, and new Widgets are discovered and some of the omitted trait values may change over time (very gradually) but the ext_id and w_code are guaranteed to be unique. Given the nature of the values for ext_id it behaves ideally as a primary key.

所有字段值都是通过外部系统提供的,并且会发现新的 Widget,并且一些省略的特征值可能会随着时间的推移(非常逐渐地)发生变化,但 ext_id 和 w_code 保证是唯一的。鉴于 ext_id 值的性质,它理想地充当主键。

However when I create a new record, specifying the ext_id value, the value is not used in storage. Instead the values in ext_id follow an auto-increment behavior.

但是,当我创建新记录并指定 ext_id 值时,该值不会在存储中使用。相反, ext_id 中的值遵循自动递增行为。

>>> # from a clean database
>>> skill = Widget(ext_id=7723, w_code=u'IGF35ac9')
>>> session.add(skill)
>>> session.commit()
>>> Skill.query.first().ext_id
1
>>> 

How can I specify to SQLAlchemy that the ext_id field should be used as the primary key field without auto-increment?

如何向 SQLAlchemy 指定 ext_id 字段应用作主键字段而不自动递增?

Note: I could add an extra synthetic id column as the primary key and make ext_id be a unique column instead but this both complicates my code and adds a (minimal) extra bloat to the database and all I/O to it. I'm hoping to avoid that.

注意:我可以添加一个额外的合成 id 列作为主键,并使 ext_id 成为一个唯一的列,但这既使我的代码复杂化,又给数据库和所有 I/O 添加了(最小的)额外膨胀。我希望避免这种情况。

Issue originated from a larger project but I was able to create a smaller repro.

问题源于一个较大的项目,但我能够创建一个较小的重现。

Testing with sqlite

使用 sqlite 进行测试

采纳答案by davidism

Set autoincrement=Falseto disable creating a sequence or serial for the primary key.

设置autoincrement=False为禁用为主键创建序列或序列。

ext_id = db.Column(db.Integer, primary_key=True, autoincrement=False)