简体   繁体   English

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

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

I'm using Flask, Alembic, and PostgreSQL with SQLAlchemy. 我正在使用Flask,Alembic和PostgreSQL与SQLAlchemy。 I have an existing table location_messages with a column campaign_id . 我有一个包含列campaign_id的现有表location_messages This was created initially in the model with the code 这是最初在模型中使用代码创建的

campaign_id = db.Column(db.Integer)

I want to add a foreign key to it, so I updated the model with 我想为它添加一个外键,所以我更新了模型

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

I ran the revision --autogenerate but it didn't create anything-- so I've been looking through the docs but I can't grok the syntax for my usage. 我运行了revision --autogenerate但它没有创建任何东西 - 所以我一直在查看文档,但我不能理解我的用法语法。 For what it's worth, creating the table from scratch (after dropping it) in Alembic is 对于它的价值,在Alembic中从头开始创建表(放下它之后)是

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

but for my life, I can't find a way to do this for an existing table. 但对于我的生活,我找不到一种方法来为现有的桌子做这件事。 Is there a way to just get an instance of a table and assign a ForeignKeyConstraint to a column? 有没有办法只获取一个表的实例并将一个ForeignKeyConstraint分配给一个列?

The Alembic op you are looking for is create_foreign_key . 您正在寻找的Alembic操作是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. 建议您使用自动约束命名,以便可以将None作为名称传递,而不是手动命名。

ForeignKey just need to be Tuple ... so instead of ['campaign_id'] write ('campaign_id',) 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