How to create postgresql's sequences in Alembic

Just add following to your model:

field_seq = Sequence('groups_field_seq')
field = Column(Integer, field_seq, server_default=field_seq.next_value())

And add following to your migration file (before creating table):

from sqlalchemy.schema import Sequence, CreateSequence
op.execute(CreateSequence(Sequence('groups_field_seq')))

Found a hint at https://bitbucket.org/zzzeek/alembic/issue/60/autogenerate-for-sequences-as-well-as#comment-4100402

Following the CreateSequence found in the previous link I still have to jump through several hoops to make my migrations works in SQLite and PostgreSQL. Currently I have:

def dialect_supports_sequences():
    return op._proxy.migration_context.dialect.supports_sequences


def create_seq(name):
    if dialect_supports_sequences():
       op.execute(CreateSequence(Sequence(name)))

And then call the create_seq whenever I need it.

Is this the best practice?


Not sure if I got your question right but as nobody else chose to answer, here is how I get perfectly normal ids:

Alembic:

op.create_table('event',
    sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False),

The class:

class Event(SQLADeclarativeBase):
    __tablename__ = 'event'
    id = Column(Integer, primary_key = True)