2017-01-08 65 views
2

當我運行下面的代碼時,我期待first_name和last_name是一個複合主鍵,而id是一個自動增量索引該行,但不能作爲主鍵,因爲表中其餘部分的信息是我需要定義它的唯一性的信息,而不是給定的ID。使用SQLAlchemy ORM作爲一個非主鍵,唯一的,自動遞增的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列是空的,而不是我期待的自動遞增整數。 Image of person table

要清楚:我的問題是:我將如何爲不是主鍵的SQLAlchemy ORM類創建自動遞增索引?

+0

如果你不需要增加,你可以使用UUID4s –

回答

3

在撰寫本文時,SQLAlchemy 1.1不支持在非主鍵字段上自動遞增。

相關問題