sqlalchemy and auto increments with postgresql

后端 未结 3 894
臣服心动
臣服心动 2021-01-13 15:37

I created a table with a primary key and a sequence but via the debug ad later looking at the table design, the sequence isn\'t applied, just created.

from s         


        
3条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-13 16:07

    I realize this is an old thread, but I stumbled on it with the same problem and were unable to find a solution anywhere else.

    After some experimenting I was able to solve this with the following code:

    TABLE_ID = Sequence('table_id_seq', start=1000)
    
    class Table(Base):
        __tablename__ = 'table'
    
        id = Column(Integer, TABLE_ID, primary_key=True, server_default=TABLE_ID.next_value())
    

    This way the sequence is created and is used as the default value for column id, with the same behavior as if created implicitly by SQLAlchemy.

提交回复
热议问题