将SQLAlchemy ORM用作非主键,唯一的自动递增ID

编程入门 行业动态 更新时间:2024-10-13 18:24:46
本文介绍了将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") ]) sessionmit()

我在DataGrip中查看结果的问题,正在获取下表.数据未按添加顺序排序,并且id列为null,而不是我期望的自动递增整数.

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

本文发布于:2023-11-28 15:09:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1642905.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:主键   SQLAlchemy   ORM   ID

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!