将 SQLAlchemy ORM 用于非主键、唯一、自动递增的 id

Using SQLAlchemy ORM for a non-primary key, unique, auto-incrementing id(将 SQLAlchemy ORM 用于非主键、唯一、自动递增的 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

基础教程推荐