[英]in sqlalchemy, how can I import existing table having foreign key on the other table
[英]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.