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
基础教程推荐
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- 在多列上分布任意行 2021-01-01
- oracle区分大小写的原因? 2021-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
