当我尝试重新初始化我的数据库时,我不断收到IntegrityError:
sqlalchemy.exc.IntegrityError: (IntegrityError) (1217, 'Cannot delete or update a parent row: a foreign key constraint fails') '\nDROP TABLE users' ()
在我的init_db脚本中,我有:
def main(argv=sys.argv):
if len(argv) != 2:
usage(argv)
config_uri = argv[1]
setup_logging(config_uri)
settings = get_appsettings(config_uri)
engine = create_engine('...')
Session.configure(bind=engine)
session = Session()
Base.metadata.bind=engine
Base.metadata.drop_all(engine)
Base.metadata.create_all(engine)
它会让我删除Users表,即:
class User(Base):
__tablename__='users'
__table_args__={
'mysql_engine':'InnoDB',
'mysql_charset':'utf8',
}
user_id = Column(Integer, primary_key=True, unique=True)
username = Column(VARCHAR(16), primary_key=True, unique=True)
name = Column(VARCHAR(16))
password = Column(VARCHAR(20))
email = Column(VARCHAR(30))
creation = Column(DateTime, default = datetime.datetime.now)
def __init__(self, un, name, pw, email):
self.username = un
self.name = name
self.email = email
self.password = pw
答案 0 :(得分:6)
我认为有两个可能的原因:
ForeignKey
到users
表,但未映射到任何sqlalchemy
模型因此在drop_all
操作期间不会被删除。sqlalchemy
模型中缺少某些关系。例如,数据库上的addresses
表有ForeignKey
表示users
表,但是您的模型Address
(或者说正确,表示映射器为Address
)不配置此ForeignKey,因此在drop_all
sqlalchemy
期间无法知道应在引用的表(users
)之前删除此表。