How can I add a foreign key constraint on an existing table column via SQLAlchemy?

The Alembic op you are looking for is create_foreign_key.

op.create_foreign_key(
    'fk_location_message_campaign',
    'location_messages', 'campaigns',
    ['campaign_id'], ['id'],
)

It is recommended that you use automatic constraint naming so that you can pass None as the name rather than naming it manually.


ForeignKey just need to be Tuple ... so instead of ['campaign_id'] write ('campaign_id',)

op.create_table('location_messages',
[...]
sa.Column('campaign_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(('campaign_id',), ['campaigns.id'], ),
sa.PrimaryKeyConstraint('id')
)