将SQLAlchemy ORM用作非主键,唯一的自动递增ID [英] Using SQLAlchemy ORM for a non-primary key, unique, auto-incrementing id

查看:144
本文介绍了将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列为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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆