繁体   English   中英

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

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

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

campaign_id = db.Column(db.Integer)

我想为它添加一个外键,所以我更新了模型

campaign_id = db.Column(db.Integer, db.ForeignKey('campaigns.id'))

我运行了revision --autogenerate但它没有创建任何东西 - 所以我一直在查看文档,但我不能理解我的用法语法。 对于它的价值,在Alembic中从头开始创建表(放下它之后)是

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

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

您正在寻找的Alembic操作是create_foreign_key

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

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

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')
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM