我有以下型号
models.py
class Rules(db.Model):
name=db.Column(db.String, primary_key=True)
rule=db.Column(db.Integer, default='0', unique=False)
def __repr__(self): # pragma: no cover
return '<Rules %r>' % (self.name)
如果我尝试在其中存储数据,它声称规则有一个独特的要求。我事件竟然明确声明unique = False,但它仍然声称它必须是唯一的以下错误
sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) UNIQUE constraint failed: rules.rule [SQL: u'INSERT INTO rules (name, rule) VALUES (?, ?)'] [parameters: ('dod_iaa_cyber', '2')]
我多次运行以下脚本尝试迁移它并修复错误无效。
db_migrate.py
#!flask/bin/python
import imp
from migrate.versioning import api
from app import db
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
v = api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
migration = SQLALCHEMY_MIGRATE_REPO + ('/versions/%03d_migration.py' % (v+1))
tmp_module = imp.new_module('old_model')
old_model = api.create_model(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
exec old_model in tmp_module.__dict__
script = api.make_update_script_for_model(SQLALCHEMY_DATABASE_URI,
SQLALCHEMY_MIGRATE_REPO,
tmp_module.meta, db.metadata)
open(migration, "wt").write(script)
api.upgrade(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
v = api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
print('New migration saved as ' + migration)
print('Current database version: ' + str(v))
007_migration.py,从003-007开始的所有迁移都与此相同
from sqlalchemy import *
from migrate import *
from migrate.changeset import schema
pre_meta = MetaData()
post_meta = MetaData()
def upgrade(migrate_engine):
# Upgrade operations go here. Don't create your own engine; bind
# migrate_engine to your metadata
pre_meta.bind = migrate_engine
post_meta.bind = migrate_engine
def downgrade(migrate_engine):
# Operations to reverse the above upgrade go here.
pre_meta.bind = migrate_engine
post_meta.bind = migrate_engine
002_migration.py,这个与其他人不同,并且将规则作为主键
from sqlalchemy import *
from migrate import *
from migrate.changeset import schema
pre_meta = MetaData()
post_meta = MetaData()
rules = Table('rules', post_meta,
Column('rule', Integer, primary_key=True, nullable=False),
Column('name', String(length=45)),
)
def upgrade(migrate_engine):
# Upgrade operations go here. Don't create your own engine; bind
# migrate_engine to your metadata
pre_meta.bind = migrate_engine
post_meta.bind = migrate_engine
post_meta.tables['rules'].create()
def downgrade(migrate_engine):
# Operations to reverse the above upgrade go here.
pre_meta.bind = migrate_engine
post_meta.bind = migrate_engine
post_meta.tables['rules'].drop()
那么为什么新的迁移没有恢复,我将规则从主键更改为只是一个整数,如何才能将其正确转换为未来呢?
答案 0 :(得分:0)
你的名字是否独一无二?拥有主键意味着该字段是唯一的。
答案 1 :(得分:0)
修复是删除models.py中的表规则然后迁移数据库,从而强制它丢弃。在病房之后,我重新添加规则并再次迁移。这次它识别出Rules.rule不是唯一的密钥并且正确迁移。
感谢帮助人员。我不确定为什么它没有发现我在迁移过程中将规则更改为标准整数,但一切都很顺利。