新迁移,添加一个简单的表,在迁移过程中给出了“无法添加外键约束”的错误。
这是一个名为EventLog
的现有模型:
class EventLog(models.Model):
"""
The event log.
"""
user = models.ForeignKey(User, blank=True, null=True)
timestamp = models.DateTimeField(auto_now=True)
text = models.TextField(blank=True, null=True)
ip = models.CharField(max_length=15)
metadata = JSONField(default={},blank=True)
product = models.TextField(default=None,blank=True, null=True)
type = models.ForeignKey(EventType)
def __unicode__(self):
return "[%-15s]-[%s] %s (%s)" % (self.type, self.timestamp, self.text, self.user)
def highlite(self):
if self.type.highlite:
return self.type.highlitecss
return False
接下来是新模型,我正在尝试创建:
class EventLogDetail(models.Model):
# NOTE: I've already tried switching 'EventLog' out for just EventLog.
eventlog = models.ForeignKey('EventLog', related_name='details')
order = models.IntegerField(default=0)
line = models.CharField(max_length=500)
class Meta:
ordering = ['eventlog', 'order']
看起来很简单吧?所以我进行了迁移:
./manage.py makemigrations
:
Migrations for 'accounts':
accounts/migrations/0016_eventlogdetail.py
- Create model EventLogDetail
到目前为止,这么好。然后,我这样迁移:
./manage.py migrate
:
Operations to perform:
Apply all migrations: accounts, admin, attention, auth, contenttypes, freedns, hosting, info, mail, sessions, sites, taggit, vserver
Running migrations:
Applying accounts.0016_eventlogdetail...Traceback (most recent call last):
File "./manage.py", line 10, in
execute_from_command_line(sys.argv)
File "/home/the_user/code/the_project/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line
utility.execute()
File "/home/the_user/code/the_project/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 355, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/the_user/code/the_project/local/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/the_user/code/the_project/local/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute
output = self.handle(*args, **options)
File "/home/the_user/code/the_project/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 204, in handle
fake_initial=fake_initial,
File "/home/the_user/code/the_project/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 115, in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
File "/home/the_user/code/the_project/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "/home/the_user/code/the_project/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 244, in apply_migration
state = migration.apply(state, schema_editor)
File "/home/the_user/code/the_project/local/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 93, in __exit__
self.execute(sql)
File "/home/the_user/code/the_project/local/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 120, in execute
cursor.execute(sql, params)
File "/home/the_user/code/the_project/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/home/the_user/code/the_project/local/lib/python2.7/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/the_user/code/the_project/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/home/the_user/code/the_project/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 101, in execute
return self.cursor.execute(query, args)
File "/home/the_user/code/the_project/local/lib/python2.7/site-packages/MySQLdb/cursors.py", line 205, in execute
self.errorhandler(self, exc, value)
File "/home/the_user/code/the_project/local/lib/python2.7/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
django.db.utils.IntegrityError: (1215, 'Cannot add foreign key constraint')
然后就是迁移本身,所有都是Pythonic的荣耀:
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-30 12:51
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('accounts', '0015_product_public'),
]
operations = [
migrations.CreateModel(
name='EventLogDetail',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('order', models.IntegerField(default=0)),
('line', models.CharField(max_length=500)),
('eventlog', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='details', to='accounts.EventLog')),
],
options={
'ordering': ['eventlog', 'order'],
},
),
]
我已经尝试重命名新模型及其中的所有内容(事件为related_name
属性),以防我使用某些机制已经采用的变量名称,但结果相同。
在线搜索,我只发现了Django(Django MySQL error when creating tables)这个问题的一个例子,但这没有帮助。没有向auth
进行迁移,也不能理解为什么会有这样的迁移,因为我们最近既未与该部分混淆也未升级任何包。
任何帮助深表赞赏。
答案 0 :(得分:0)
更改
eventlog = models.ForeignKey('EventLog', related_name='details')
到
eventlog = models.ForeignKey(EventLog, related_name='details')
)
答案 1 :(得分:0)
尝试删除引号:
foreach
或者如果你想使用引用,那么也使用app_name
eventlog = models.ForeignKey(EventLog, related_name='details')
答案 2 :(得分:0)
好的,想通了。
我尝试手动创建外键,然后使用相同的神秘错误消息失败。在寻找完全专注于MySQL的解决方案时,我在这里找到了@Andrew的答案:MySQL Cannot Add Foreign Key Constraint,详细说明了外键的要求。
其中一个要求是两个表使用相同的引擎类型,可以是InnoDB或MyISAM。事实证明,在我的数据库中,旧表是MyISAM,而较新的表是InnoDB,事实上,这是我问题的根源。
我写了一个简短且非常凌乱的shell脚本来修复问题,你可以在下面看到。请注意,它既没有写出性能也没有美丽。只是想把它结束。
#!/bin/bash
DBNAME=excellent_database
PASSWORD=very-very-bad-password-on-many-sides-on-many-sides
# Some of the datetime data in the old MyISAM tables were giving
# InnoDB a rough time so here they are updated to something InnoDB
# feels more comfortable with. Subqueries didn't work and I
# couldn't be bothered to figure out why.
IDS=$(mysql "$DBNAME" -u root -p"$PASSWORD" -e "SELECT id FROM appname_modelname WHERE timestamp_created = '0000-00-00 00:00:00';")
for ROW_ID in $IDS; do
mysql "$DBNAME" -u root -p"$PASSWORD" -e "UPDATE appname_modelname SET timestamp_created = '0001-01-01 00:00:00' WHERE id = $ROW_ID";
echo $ROW_ID
done
mysql "$DBNAME" -u root -p"$PASSWORD" -e "SHOW TABLE STATUS WHERE ENGINE = 'MyISAM';" | awk 'NR>1 {print "ALTER TABLE "$1" ENGINE = InnoDB;"}' | mysql -u root -p"$PASSWORD" "$DBNAME"
希望它可以帮助别人!
答案 3 :(得分:0)
我的问题是我的Django项目中的数据库是从头创建的,而表是从mysql dump导入的。 mysql dump中的表是CHARSET utf8mb4
,而我使用迁移创建的新表是使用CHARSET latin1
创建的。因此,新外键是在带有latin1
的表中创建的,并引用带有utf8mb4
的表,这会引发错误
Django:django.db.utils.IntegrityError:(1215,'无法添加外键 约束')
新表是用CHARSET latin1
创建的,因为我创建的数据库的默认CHARSET是latin1
。要检查默认的CHARSET,请在mysql控制台中输入以下命令。
mysql> SELECT default_character_set_name FROM information_schema.SCHEMATA S WHERE schema_name = "DBNAME";
此问题的解决方法是将数据库的默认CHARSET转换为utf8mb4
。如果CHARSET不是utf8,这不仅需要解决完整性错误,而且Django还有很多其他问题。要更改数据库的CHARSET,请使用此命令。
mysql> ALTER DATABASE DBNAME CHARACTER SET utf8 COLLATE utf8_general_ci;