Django:django.db.utils.IntegrityError:(1215,'无法添加外键约束')

Tee*_*kin 4 django django-migrations

新的迁移(添加一个简单的表)在迁移过程中给出错误“无法添加外键约束”。

这是一个现有的模型,称为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
Run Code Online (Sandbox Code Playgroud)

这是我正在尝试创建的新模型:

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']
Run Code Online (Sandbox Code Playgroud)

看起来很简单,对吧?所以我进行迁移:

./manage.py makemigrations

Migrations for 'accounts':
  accounts/migrations/0016_eventlogdetail.py
    - Create model EventLogDetail
Run Code Online (Sandbox Code Playgroud)

到目前为止,一切都很好。然后,我迁移,如下所示:

./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')
Run Code Online (Sandbox Code Playgroud)

这就是迁移本身,充满了Python式的荣耀:

# -*- 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'],
            },
        ),
    ]
Run Code Online (Sandbox Code Playgroud)

我尝试重命名新模型及其中的所有内容(事件属性related_name),以防我使用引擎盖下的某些机器已经采用的变量名称,但结果相同。

在网上搜索时,我只找到了一个专门针对 Django 的问题的示例(创建表时的 Django MySQL 错误),但这并没有帮助。不需要迁移到auth,我也不明白为什么会迁移,因为我们最近既没有弄乱该部分,也没有升级任何软件包。

任何帮助深表感谢。

San*_*pal 8

我的问题是我的 Django 项目中的数据库是从头开始创建的,表是从 mysql 转储导入的。mysql 转储中的表是 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";
Run Code Online (Sandbox Code Playgroud)

此问题的解决方法是将数据库的默认 CHARSET 转换为utf8mb4. 这不仅是修复完整性错误所必需的,而且如果 CHARSET 不是 utf8,Django 还会遇到许多其他问题。要更改数据库的 CHARSET,请使用此命令。

mysql> ALTER DATABASE DBNAME CHARACTER SET utf8 COLLATE utf8_general_ci;
Run Code Online (Sandbox Code Playgroud)