簡體   English   中英

django.db.utils.OperationalError: 1005, 'Can't create table `xyz`.`#sql-600_237` (errno: 150 "外鍵約束格式不正確")

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

我正在嘗試將一對一密鑰添加到我的 Django 應用程序中,但是當我嘗試“遷移”過程時總是會出現該錯誤(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')),
        ],
    ),
]

但是,即使在遷移錯誤之后,當我對其進行測試時,一切正常。 但是,如果在“遷移”期間出現該錯誤消息,那應該不是好事。 如果沒有問題,是否可以跳過使我的遷移崩潰的最后一步?

有人可以說我為什么會收到該錯誤消息以及如何解決它?

非常感謝您,祝您有美好的一天!

我找到了一個解決方案,可能不是更清潔,但該死的它有效,這對我來說是完美的。

# -*- 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 表都使用相同的存儲引擎(即 MyISM v. InnoDB)。 特別是它們之間有外鍵的表。

如果您需要更多關於 MySQL 存儲引擎的信息以及如何知道您使用的是哪一個,您需要閱讀 MySQL 文檔,盡管我們數據庫文檔中的 MySQL 注釋也有一些介紹性信息。

我懷疑您使用 MyISAM 存儲引擎(MySQL < 5.5 的默認值)創建了表,並且由於 MySQL 5.5 默認為 InnoDB 並且您從那時起創建了新表,您以混合結束

您可以從 phpMyadmin 更改表存儲引擎。 單擊您的 teble 名稱,轉到“操作”選項卡,然后在“表操作”框中進行更改。 將所有或您的存儲引擎轉換為相同的。

Look at the output of the command SHOW ENGINE INNODB STATUS in MySql or MariaDB console client ( mariadb link , mysql link ). 它比錯誤消息提供更多信息。 例如,它向我顯示了這條消息:

...
------------------------
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`)'.
...

它對我說我忘了創建遷移。

首先要做的應該是檢查表的存儲引擎。 但是,在我的情況下,存儲引擎是相同的(都是 INNODB)。 我的問題是無與倫比的表格collation 設置數據庫的默認字符集后,我的問題已經解決。

您可以通過以下方式查看表格詳細信息;

SHOW TABLE STATUS WHERE Name = "yyyyyyy";

一旦你弄清楚你的表(將是 ForeignKey)排序規則,你可以設置你的數據庫默認字符集,如下所示

ALTER DATABASE my_db COLLATE = 'latin1_swedish_ci';

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM