Using SQLAlchemy ORM for a non-primary key, unique, auto-incrementing id(将 SQLAlchemy ORM 用于非主键、唯一、自动递增的 id)
问题描述
当我运行以下代码时,我希望 first_name 和 last_name 是复合主键,而 id 是该行的自动递增索引,但不充当主键,因为有信息在表格的其余部分是我需要定义它的唯一性,而不是给定的 ID.
When I run the following code, I am expecting the first_name, and last_name to be a composite primary key and for the id to be an autoincrementing index for the row, but not to act as the primary key, as there the information in the rest of the table is what I need to define it's uniqueness, rather than the given ID.
Base = declarative_base()
Session = sessionmaker(bind=db)
session = Session()
class Person(Base):
__tablename__ = "people"
id = Column(Integer, index=True, unique=True, autoincrement=True, primary_key=False)
first_name = Column(String(30), primary_key=True)
last_name = Column(String(30), primary_key=True)
if __name__ == "__main__":
Base.metadata.create_all(db)
session.add_all([
Person(first_name="Winston", last_name="Moy"),
Person(first_name="Bill", last_name="Gates"),
Person(first_name="Steve", last_name="Jobs"),
Person(first_name="Quinten", last_name="Coldwater")
])
session.commit()
问题我在DataGrip中查看结果,得到下表.数据不在添加的顺序中,并且 id 列为空,而不是我期望的自动递增整数.
The problem I view the results in DataGrip, I'm getting the following table. The data is not in the order added, and the id column is null, instead of the auto-incrementing integer I'm expecting it to be.
要明确:我的问题是:如何为不是主键的 SQLAlchemy ORM 类创建自动递增索引?
To be clear: My question is: How would I make an auto-incrementing index for a SQLAlchemy ORM class that is not a primary key?
推荐答案
在撰写本文时,SQLAlchemy 1.1 不支持非主键字段的自动递增.
At the time of writing this, SQLAlchemy 1.1 does not support auto-incrementing on a non-primary key field.
这篇关于将 SQLAlchemy ORM 用于非主键、唯一、自动递增的 id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将 SQLAlchemy ORM 用于非主键、唯一、自动递增的 id


- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- SQL 临时表问题 2022-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 更改自动增量起始编号? 2021-01-01