【问题标题】:Django: django.db.utils.IntegrityError: (1215, 'Cannot add foreign key constraint')Django:django.db.utils.IntegrityError:(1215,'无法添加外键约束')
【发布时间】:2018-02-08 04:24:31
【问题描述】:

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

这是一个现有模型,名为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')

这就是迁移本身,总之是 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'],
            },
        ),
    ]

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

在网上搜索,我只找到了一个与 Django 相关的这个问题的例子(Django MySQL error when creating tables),但这并没有帮助。没有要迁移到 auth 的迁移,我也不明白为什么会迁移,因为我们最近既没有弄乱那部分也没有升级任何包。

非常感谢任何帮助。

【问题讨论】:

  • 您是否尝试过从“EventLog”中删除引号
  • 是的,我有。没什么区别。不过谢谢。 :)

标签: django django-migrations


【解决方案1】:

我的问题是我的 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";

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

mysql> ALTER DATABASE DBNAME CHARACTER SET utf8 COLLATE utf8_general_ci;

【讨论】:

    【解决方案2】:

    好的,想通了。

    我尝试手动创建外键,然后失败并显示相同的神秘错误消息。在搜索完全专注于 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】:

      改变

      eventlog = models.ForeignKey('EventLog', related_name='details')
      

      eventlog = models.ForeignKey(EventLog, related_name='details')
      

      ;)

      【讨论】:

      • 没有区别。不过谢谢。 :)
      • 请发帖django_migrations表。
      • 好问题,@campovski,但我找到了解决方案并将其发布在上面。 :) 感谢您的关注。
      【解决方案4】:

      尝试删除引号:

      eventlog = models.ForeignKey(EventLog, related_name='details')
      

      或者如果你想使用引号,那么也使用 app_name

      eventlog = models.ForeignKey('accounts.EventLog', related_name='details')
      

      【讨论】:

      • 试过了。结果相同。感谢您的回复。 :)
      猜你喜欢
      • 2017-07-16
      • 2015-01-24
      • 2015-02-04
      • 2016-05-15
      • 2017-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多