Django:django.db.utils.完整性错误:(1215,“无法添加外键约束”)

ut6juiuv  于 2022-12-14  发布在  Go
关注(0)|答案(5)|浏览(205)

新的迁移添加了一个简单的表,在迁移过程中出现错误“Cannot add foreign key constraint”(无法添加外键约束)。
下面是一个名为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,我也不明白为什么会有,因为我们最近既没有弄乱这部分,也没有升级任何包。
任何帮助深表感谢。

nfzehxib

nfzehxib1#

我的问题是Django项目中的数据库是从零开始创建的,表是从mysql转储导入的。mysql转储中的表是CHARSET utf8mb4,而我使用迁移创建的新表是用CHARSET latin1创建的。因此,新外键是在一个用latin1创建的表中创建的,并且引用了一个用utf8mb4创建的表,这会引发错误
Django:django.db.utils.完整性错误:(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;
px9o7tmv

px9o7tmv2#

好吧,我知道了。
我尝试手动创建外键,但失败了,并显示同样的错误信息。搜索完全针对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"

希望对别人有帮助!

niwlg2el

niwlg2el3#

尝试删除报价:

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

或者,如果要使用引号,则还可以使用app_name

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

6yt4nkrj4#

我在尝试创建一个指向products. Transaction的common.Activity外键时遇到了这个错误。
我的答案不是原创的,但我整理了一些答案,因为它们没有指定非常重要的内容。utf8!= utf8 mb 4,如果您的表有这种差异,FK迁移仍然会崩溃
要查找已分配给表的字符集

SELECT CCSA.character_set_name 
FROM information_schema.`TABLES` T,information_schema.`COLLATION_CHARACTER_SET_APPLICABILITY` CCSA
WHERE CCSA.collation_name = T.table_collation
AND T.table_schema = "cart_live"
AND T.table_name = "products_transaction";
| latin1             |
+--------------------+
SELECT CCSA.character_set_name 
FROM information_schema.`TABLES` T,information_schema.`COLLATION_CHARACTER_SET_APPLICABILITY` CCSA
WHERE CCSA.collation_name = T.table_collation
AND T.table_schema = "cart_live"
AND T.table_name = "common_activity";
| utf8               |

注意:它们必须完全相同!latin 1!= utf8!= utf8 mb 4要查看您的字符集版本....

mysql> SHOW VARIABLES WHERE Variable_name LIKE 'character\_set\_%' OR 
Variable_name LIKE 'collation%';
    +--------------------------+-------------------+
| Variable_name            | Value             |
+--------------------------+-------------------+
| character_set_client     | utf8              |
| character_set_connection | utf8              |
| character_set_database   | latin1            |
| character_set_filesystem | binary            |
| character_set_results    | utf8              |
| character_set_server     | latin1            |
| character_set_system     | utf8              |
| collation_connection     | utf8_general_ci   |
| collation_database       | latin1_swedish_ci |
| collation_server         | latin1_swedish_ci |
+--------------------------+-------------------+

我使用了utf8_general_ci,如下所示

ALTER TABLE products_transaction CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;
mysql> SELECT CCSA.character_set_name 
    -> FROM information_schema.`TABLES` T,information_schema.`COLLATION_CHARACTER_SET_APPLICABILITY` CCSA
    -> WHERE CCSA.collation_name = T.table_collation
    -> AND T.table_schema = "cart_live"
    -> AND T.table_name = "products_transaction";
| utf8               |

然后运行迁移以添加外键

sq1bmfud

sq1bmfud5#

变更

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

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

;)

相关问题