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

2024-05-10 06:29:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Flask、Alembic和PostgreSQL和SQLAlchemy。我有一个表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分配给一个列?


Tags: 模型idflaskdbsqlalchemypostgresqlsacolumn
2条回答

外键只需要是元组。。。所以写['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')
)

您要找的Alembic op是^{}

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

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

相关问题 更多 >