django.db.utils.OperationalError: 1005, 'Can't create table `xyz`.`#sql-600_237` (errno: 150 "Foreign key constraint is incorrectly formed")

django.db.utils.OperationalError: 1005, 'Can't create table `xyz`.`#sql-600_237` (errno: 150 "Foreign key constraint is incorrectly formed")

我正在尝试将一对一密钥添加到我的 Django 应用程序中,但是当我尝试 "migrate" 处理(makemigrations 效果很好)时,我总是会遇到该错误。

  Applying xyzapp.0007_personne_extended_foreign...Traceback (most recent call last):
  File "manage.py", line 29, in <module>
    execute_from_command_line(sys.argv)
  File "/opt/xyz/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line
utility.execute()
  File "/opt/xyz/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 346, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/opt/xyz/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 394, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/opt/xyz/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 445, in execute
    output = self.handle(*args, **options)
  File "/opt/xyz/env/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 222, in handle
    executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
  File "/opt/xyz/env/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 110, in migrate
    self.apply_migration(states[migration], migration, fake=fake, fake_initial=fake_initial)
  File "/opt/xyz/env/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 148, in apply_migration
    state = migration.apply(state, schema_editor)
  File "/opt/xyz/env/local/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 91, in __exit__
    self.execute(sql)
  File "/opt/xyz/env/local/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 111, in execute
    cursor.execute(sql, params)
  File "/opt/xyz/env/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/opt/xyz/env/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/opt/xyz/env/local/lib/python2.7/site-packages/django/db/utils.py", line 98, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/opt/xyz/env/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/opt/xyz/env/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 124, in execute
    return self.cursor.execute(query, args)
  File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 226, in execute
    self.errorhandler(self, exc, value)
  File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
    raise errorvalue
django.db.utils.OperationalError: (1005, 'Can\'t create table `xyz`.`#sql-600_297` (errno: 150 "Foreign key constraint is incorrectly formed")')

这就是我的模型的样子:

class PersonVolunteer(models.Model):
    person = models.OneToOneField(Person)

class Person(models.Model):
    name = models.CharField(max_length=100)

以及导致崩溃的迁移过程:

class迁移(migrations.Migration):

dependencies = [
    ('xyzapp', '0014_member_to_person'),
]

operations = [
    migrations.CreateModel(
        name='PersonVolunteer',
        fields=[
            ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
            ('personne', models.OneToOneField(to='xyzapp.Personne')),
        ],
    ),
]

但是,即使在迁移错误之后,我测试它时一切正常。但是,如果在 "migrate" 期间出现该错误消息,那应该不是什么好事。如果没有问题,可以跳过导致我的迁移崩溃的最后一步吗?

有人可以告诉我为什么会收到该错误消息以及如何解决吗?

非常感谢,祝您愉快!

我找到了一个解决方案,可能不是更清洁的解决方案,但该死的它有效,这对我来说是完美的。

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('cvmapp', '0006_person_extended'),
    ]

    operations = [
        migrations.AddField(
            model_name='PersonVolunteer',
            name='personne',
            field=models.OneToOneField(related_name='info_volunteer', to='cvmapp.Person', db_constraint=False),
        ),
    ]

诀窍是添加 "db_constraint=False" 作为 OneToOne 字段的参数。

请确保您所有的 MySQL table 都使用相同的存储引擎(即 MyISM 与 InnoDB)。特别是 table 之间有外键。

如果您需要有关 MySQL 存储引擎的更多信息以及如何知道您使用的是哪个存储引擎,您将需要阅读 MySQL 文档,尽管 MySQL我们数据库文档中的注释也有一些介绍性信息。

我怀疑您使用 MyISAM 存储引擎创建了 tables(MySQL < 5.5 的默认设置)并且因为 MySQL 5.5 默认为 InnoDB 并且您创建了新的 tables 从那时起,你以混音结束

您可以从 phpMyadmin 更改 table 存储引擎。单击您的表名,转到 'operations' 选项卡,然后在“Table 操作”框中进行更改。将所有或您的存储引擎转换为相同的。

查看 MySql 或 MariaDB 控制台客户端 (mariadb link, mysql link) 中命令 SHOW ENGINE INNODB STATUS 的输出。它比错误消息信息更丰富。 例如,它向我展示了这条消息:

...
------------------------
LATEST FOREIGN KEY ERROR
------------------------
2021-09-20 18:27:08 7faea3ad1700 Error in foreign key constraint of table `my_db`.`django_admin_log`:
Alter  table `my_db`.`django_admin_log` with foreign key constraint failed. Referenced table `my_db`.`profiles_userprofile` not found in the data dictionary near ' FOREIGN KEY (`user_id`) REFERENCES `profiles_userprofile` (`id`)'.
...

它对我说我忘记创建迁移了。