sqlalchemy and auto increments with postgresql

后端 未结 3 848
臣服心动
臣服心动 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:06

    I ran into a similar issue with composite multi-column primary keys. The SERIAL is only implicitly applied to a single column primary key. However, this behaviour can be controlled via the autoincrement argument (defaults to "auto"):

    id = Column(Integer, primary_key=True, autoincrement=True)
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-13 16:12

    You specified an explicit Sequence() object with name. If you were to omit that, then SERIAL would be added to the id primary key specification:

    CREATE TABLE tramos (
        id INTEGER SERIAL NOT NULL, 
        nombre VARCHAR, 
        tramo_data VARCHAR, 
        estado BOOLEAN, 
        PRIMARY KEY (id)
    )
    

    A DEFAULT is only generated if the column is not a primary key.

    When inserting, SQLAlchemy will issue a select nextval(..) as needed to create a next value. See the PostgreSQL documentation for details.

    0 讨论(0)
提交回复
热议问题