简体   繁体   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")

I am trying to add One-to-One keys into my Django app, but I always get that error when I try to "migrate" process (makemigrations works great).我正在尝试将一对一密钥添加到我的 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")')

That's what my models looks like:这就是我的模型的样子:

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

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

And the migration process that cause the crash:以及导致崩溃的迁移过程:

class Migration(migrations.Migration): 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')),
        ],
    ),
]

However, all works correctly when I test it even after the migrate error.但是,即使在迁移错误之后,当我对其进行测试时,一切正常。 But if that error message appears during "migrate", that should not be something good happening.但是,如果在“迁移”期间出现该错误消息,那应该不是好事。 If there's no problem, it is possible to skip that last step which crash my migration?如果没有问题,是否可以跳过使我的迁移崩溃的最后一步?

Can someone can say me why do I get that error message and how I can resolve it?有人可以说我为什么会收到该错误消息以及如何解决它?

Thank you very much and have a great day !非常感谢您,祝您有美好的一天!

I have found a solution, may be not the cleaner, but god dammit it works, that's perfect for me.我找到了一个解决方案,可能不是更清洁,但该死的它有效,这对我来说是完美的。

# -*- 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),
        ),
    ]

The trick was to add "db_constraint=False" as a parameter of the OneToOne field.诀窍是添加“db_constraint=False”作为 OneToOne 字段的参数。

Please make sure all your MySQL tables are using the same storage engine (ie MyISM v. InnoDB).请确保您的所有 MySQL 表都使用相同的存储引擎(即 MyISM v. InnoDB)。 Especially tables that have ForeignKeys between them.特别是它们之间有外键的表。

If you need more information about MySQL storage engines and how to know which one(s) are you using you will need to read the MySQL documentation, although the MySQL notes in our database docs also have some introductory information.如果您需要更多关于 MySQL 存储引擎的信息以及如何知道您使用的是哪一个,您需要阅读 MySQL 文档,尽管我们数据库文档中的 MySQL 注释也有一些介绍性信息。

I suspect you had tables created with the MyISAM storage engine (the default for MySQL < 5.5) and since MySQL 5.5 defaults to InnoDB and you created new tables since then, you ended with a mix我怀疑您使用 MyISAM 存储引擎(MySQL < 5.5 的默认值)创建了表,并且由于 MySQL 5.5 默认为 InnoDB 并且您从那时起创建了新表,您以混合结束

You can change the table storage engine from phpMyadmin.您可以从 phpMyadmin 更改表存储引擎。 Click on your teble name, go to the 'operations' tab, and change in the "Table Operation" box.单击您的 teble 名称,转到“操作”选项卡,然后在“表操作”框中进行更改。 Convert all or your storage engine to the same.将所有或您的存储引擎转换为相同的。

Look at the output of the command SHOW ENGINE INNODB STATUS in MySql or MariaDB console client ( mariadb link , mysql link ). Look at the output of the command SHOW ENGINE INNODB STATUS in MySql or MariaDB console client ( mariadb link , mysql link ). It`s more informative than error message.它比错误消息提供更多信息。 For example, it showed me this message:例如,它向我显示了这条消息:

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

It said to me that I forgot to create migrations.它对我说我忘了创建迁移。

First thing to do should be checking table's storage engines.首先要做的应该是检查表的存储引擎。 However, in my case storage engines were same (both INNODB).但是,在我的情况下,存储引擎是相同的(都是 INNODB)。 My issue was unmatched collation of tables.我的问题是无与伦比的表格collation After setting default char-set of the Database, my problem has been solved.设置数据库的默认字符集后,我的问题已经解决。

You can check table details with;您可以通过以下方式查看表格详细信息;

SHOW TABLE STATUS WHERE Name = "yyyyyyy";

Once you figure out your table's (that will be ForeignKey) collation, you can set your database default char-set as shown here like this:一旦你弄清楚你的表(将是 ForeignKey)排序规则,你可以设置你的数据库默认字符集,如下所示

ALTER DATABASE my_db COLLATE = 'latin1_swedish_ci';

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Django 迁移外键 django.db.utils.OperationalError: (1005, &quot;Can&#39;t create table &#39;asp052mysqlpy.#sql-6ac_56&#39; (errno: 150)&quot;) 错误 - Django migrating foreign keys django.db.utils.OperationalError: (1005, "Can't create table 'asp052mysqlpy.#sql-6ac_56' (errno: 150)") error Django 1.8 应用程序初始迁移神秘失败,原因是错误号:150“外键约束形成不正确” - Django 1.8 app mysteriously fails with initial migration due to errno: 150 "Foreign key constraint is incorrectly formed" django.db.utils.OperationalError: 没有这样的表 Django 2 - django.db.utils.OperationalError: no such table Django 2 django.db.utils.OperationalError: 没有这样的表 - django.db.utils.OperationalError: no such table PythonAnywhere:django.db.utils.OperationalError:没有这样的表: - PythonAnywhere: django.db.utils.OperationalError: no such table: django.db.utils.OperationalError:外键不匹配-引用“ transcript_userprofile”的“ django_admin_log” - django.db.utils.OperationalError: foreign key mismatch - “django_admin_log” referencing “transcript_userprofile” django.db.utils.OperationalError:外键不匹配 - “project_projectpage”引用“auth_user” - django.db.utils.OperationalError: foreign key mismatch - "project_projectpage" referencing "auth_user" Django 2.2 - django.db.utils.OperationalError: 没有这样的表 - Django 2.2 - django.db.utils.OperationalError: no such table django.db.utils.OperationalError:没有这样的表:django_site - django.db.utils.OperationalError: no such table: django_site Django迁移django.db.utils.OperationalError:没有这样的表: - Django migrate django.db.utils.OperationalError: no such table:
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM