How do I set an initial value for a primary key set to automatically increment using SQLAlchemy/Alembic?

StackOverflow https://stackoverflow.com/questions/13035061

  •  13-07-2021
  •  | 
  •  

Question

In MySQL, we can use AUTO_INCREMENT = ? to automatically insert a primary key value. How do we do it in SQLAlchemy/Alembic? Thanks very much!

Was it helpful?

Solution

auto_increment is emitted within a CREATE TABLE if the type is "Integer, primary_key=True". Within Alembic using alter_column, you need to specify it to alter_column.

See "autoincrement" and "existing_autoincrement" for alter_column() at:

https://alembic.readthedocs.org/en/latest/ops.html#alembic.operations.Operations.alter_column

See autoincrement for Column, note this defaults to True and you normally don't need to change it, at:

http://docs.sqlalchemy.org/en/rel_0_7/core/schema.html#sqlalchemy.schema.Column.__init__

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top