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
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)
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.
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.