如何通过SQLAlchemy在现有表列上添加外键约束?

时间:2014-12-18 22:33:47

标签: python flask sqlalchemy flask-sqlalchemy alembic

我在SQLAlchemy中使用Flask,Alembic和PostgreSQL。我有一个包含location_messages列的现有表campaign_id。这最初是在代码

的模型中创建的
campaign_id = db.Column(db.Integer)

我想为它添加一个外键,所以我用

更新了模型
campaign_id = db.Column(db.Integer, db.ForeignKey('campaigns.id'))

我运行了revision --autogenerate,但它没有创建任何内容 - 所以我一直在浏览docs,但我无法理解我的使用方法。对于它的价值,在Alembic中从头开始创建表(之后)是

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

但是对于我的生活,我无法找到一种方法来为现有的桌子做这件事。有没有办法只获取一个表的实例并为列分配ForeignKeyConstraint

2 个答案:

答案 0 :(得分:11)

您正在寻找的Alembic操作是create_foreign_key

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

建议您使用automatic constraint naming,以便您可以将None作为名称传递,而不是手动命名。

答案 1 :(得分:2)

ForeignKey只需要是元组...因此,不用['campaign_id']('campaign_id',)

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