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

Question:

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

  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):

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 !

Asked By: user1270589

||

Answers:

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.

Answered By: user1270589

Please make sure all your MySQL tables are using the same storage engine (i.e. 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.

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

You can change the table storage engine from phpMyadmin. Click on your teble name, go to the ‘operations’ tab, and change in the "Table Operation" box. Convert all or your storage engine to the same.

Answered By: Harun-Ur-Rashid

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.

Answered By: Alexander Salykin

First thing to do should be checking table’s storage engines. However, in my case storage engines were same (both INNODB). My issue was unmatched collation of tables. 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:

ALTER DATABASE my_db COLLATE = 'latin1_swedish_ci';
Answered By: dauut
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.