【问题标题】:How can I add a foreign key constraint on an existing table column via SQLAlchemy?如何通过 SQLAlchemy 在现有表列上添加外键约束?
【发布时间】:2015-02-17 20:23:48
【问题描述】:

我将 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 分配给列?

【问题讨论】:

    标签: python flask sqlalchemy flask-sqlalchemy alembic


    【解决方案1】:

    您要查找的 Alembic 操作是 create_foreign_key

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

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

    【讨论】:

      【解决方案2】:

      ForeignKey 只需要是 Tuple ... 所以而不是 ['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')
      )
      

      【讨论】:

      • 我投了反对票,因为这与问题无关。 OP 正在询问如何将外键添加到 existing 表中。您的代码显示了如何使用外键创建新表。
      猜你喜欢
      • 2018-03-05
      • 2018-11-05
      • 1970-01-01
      • 1970-01-01
      • 2021-07-10
      • 2011-02-18
      • 2017-06-10
      • 2011-01-26
      • 1970-01-01
      相关资源
      最近更新 更多