Sqlalchemy Alembic:如何向现有列添加唯一约束
我有一个表“test”,它的列“Name”没有约束。我需要Sqlalchemy Alembic:如何向现有列添加唯一约束,sqlalchemy,flask-sqlalchemy,alembic,Sqlalchemy,Flask Sqlalchemy,Alembic,我有一个表“test”,它的列“Name”没有约束。我需要通过给这个列一个唯一的约束来修改它。我该怎么做 我应该使用op.alter_列('???')还是创建唯一约束('???')? 是否为新列而不是现有列创建唯一约束?要添加,您需要: 要放弃,您需要: 注意:SQLAlchemy迁移 更新=版本:0.7.3 要添加唯一约束,请在UniqueConstraint上使用create() 要删除唯一约束,请在UniqueConstraint上使用drop() 创建迁移脚本。可以通过两种方式创建脚
通过给这个列一个唯一的约束来修改它。我该怎么做
我应该使用op.alter_列('???')
还是创建唯一约束('???')
?
是否为新列而不是现有列创建唯一约束?要添加,您需要:
要放弃,您需要:
注意:SQLAlchemy迁移
更新=版本:0.7.3
要添加唯一约束,请在UniqueConstraint上使用create()
要删除唯一约束,请在UniqueConstraint上使用drop()
创建迁移脚本。可以通过两种方式创建脚本
# create manage.py
migrate manage manage.py --repository=migrations --url=postgresql://<user>:<password>@localhost:5432/<db_name>
# create script file
python manage.py script "Add Unique Contraints"
op.drop_constraint('uq_user_name', 'user', schema='my_schema')
# create manage.py
migrate manage manage.py --repository=migrations --url=postgresql://<user>:<password>@localhost:5432/<db_name>
# create script file
python manage.py script "Add Unique Contraints"
migrate script --repository=migrations --url=postgresql://<user>:<password?@localhost:5432/<db_name> "Add Unique Contraint"
from migrate import UniqueConstraint
from sqlalchemy import MetaData, Table
def upgrade(migrate_engine):
# Upgrade operations go here. Don't create your own engine; bind
# migrate_engine to your metadata
# Table Name: user_table
# Column Name: first_name
metadata = MetaData(bind=migrate_engine)
user_table = Table('user_table', metadata, autoload=True)
UniqueConstraint(user_table.c.first_name, table=user_table).create()
def downgrade(migrate_engine):
# Operations to reverse the above upgrade go here.
# Table Name: user_table
# Column Name: first_name
metadata = MetaData(bind=migrate_engine)
user_table = Table('user_table', metadata, autoload=True)
UniqueConstraint(user_table.c.first_name, table=user_table).drop()