Тест Django «django.db.utils.IntegrityError: (1215,« Невозможно добавить ограничение внешнего ключа »)» - PullRequest
0 голосов
/ 22 февраля 2019

Django 2.1.5, с бэкэндом MySQL.

Мое приложение django работает.Этот вопрос о тесте.Добавлен запрос распечаток в коде django, в этой строке он не работает:

ALTER TABLE `documents` 
ADD CONSTRAINT`documents_assessment_perspecti_2890f0af_fk_assess_pe` 
FOREIGN KEY (`assessment_perspective`) REFERENCES `assess_perspectives` (`id`)

Я попал в MySQL с помощью инструмента командной строки и обнаружил, что в test_db таблица «assign_perspectives» не была создана, когда вышеупомянутыйкоманда внешнего ключа выполнена.Интересно, как Django определяет последовательность создания таблиц во время тестовых прогонов?Это ошибка в Django, или я не правильно ее использую?Есть ли способ, которым я могу заставить таблицу 'analysis_perspective' сначала создать тест?

Чтобы выполнить тест python manage.py test document --settings=myapp.settings.local

Моя упрощенная модель

class AssessPerspective(models.Model):
    _id = models.AutoField(db_column='id', primary_key=True)
    name = models.CharField(db_column='name', max_length=255, blank=True, null=True)

class Documents(models.Model):
    assessment_perspective = models.ForeignKey(AssessPerspective, models.DO_NOTHING, db_column='assessment_perspective', blank=True, null=True)
    ......

Исключение

Traceback (most recent call last):
  File "/Users/xxx/myapp/env/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "/Users/xxx/myapp/see/env/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 71, in execute
    return self.cursor.execute(query, args)
  File "/Users/xxx/myapp/see/env/lib/python3.7/site-packages/MySQLdb/cursors.py", line 198, in execute
    res = self._query(query)
  File "/Users/xxx/myapp/see/env/lib/python3.7/site-packages/MySQLdb/cursors.py", line 306, in _query
    db.query(q)
  File "/Users/xxx/myapp/see/env/lib/python3.7/site-packages/MySQLdb/connections.py", line 217, in query
    _mysql.connection.query(self, query)
MySQLdb._exceptions.IntegrityError: (1215, 'Cannot add foreign key constraint')

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "/Users/xxx/myapp/see/env/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "/Users/xxx/myapp/see/env/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Users/xxx/myapp/see/env/lib/python3.7/site-packages/django/core/management/commands/test.py", line 26, in run_from_argv
    super().run_from_argv(argv)
  File "/Users/xxx/myapp/see/env/lib/python3.7/site-packages/django/core/management/base.py", line 316, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/Users/xxx/myapp/see/env/lib/python3.7/site-packages/django/core/management/base.py", line 353, in execute
    output = self.handle(*args, **options)
  File "/Users/xxx/myapp/see/env/lib/python3.7/site-packages/django/core/management/commands/test.py", line 56, in handle
    failures = test_runner.run_tests(test_labels)
  File "/Users/xxx/myapp/see/env/lib/python3.7/site-packages/django/test/runner.py", line 604, in run_tests
    old_config = self.setup_databases()
  File "/Users/xxx/myapp/see/env/lib/python3.7/site-packages/django/test/runner.py", line 551, in setup_databases
    self.parallel, **kwargs
  File "/Users/xxx/myapp/see/env/lib/python3.7/site-packages/django/test/utils.py", line 174, in setup_databases
    serialize=connection.settings_dict.get('TEST', {}).get('SERIALIZE', True),
  File "/Users/xxx/myapp/see/env/lib/python3.7/site-packages/django/db/backends/base/creation.py", line 68, in create_test_db
    run_syncdb=True,
  File "/Users/xxx/myapp/see/env/lib/python3.7/site-packages/django/core/management/__init__.py", line 148, in call_command
    return command.execute(*args, **defaults)
  File "/Users/xxx/myapp/see/env/lib/python3.7/site-packages/django/core/management/base.py", line 353, in execute
    output = self.handle(*args, **options)
  File "/Users/xxx/myapp/see/env/lib/python3.7/site-packages/django/core/management/base.py", line 83, in wrapped
    res = handle_func(*args, **kwargs)
  File "/Users/xxx/myapp/see/env/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 203, in handle
    fake_initial=fake_initial,
  File "/Users/xxx/myapp/see/env/lib/python3.7/site-packages/django/db/migrations/executor.py", line 117, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "/Users/xxx/myapp/see/env/lib/python3.7/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "/Users/xxx/myapp/see/env/lib/python3.7/site-packages/django/db/migrations/executor.py", line 244, in apply_migration
    state = migration.apply(state, schema_editor)
  File "/Users/xxx/myapp/see/env/lib/python3.7/site-packages/django/db/backends/base/schema.py", line 106, in __exit__
    self.execute(sql)
  File "/Users/xxx/myapp/see/env/lib/python3.7/site-packages/django/db/backends/base/schema.py", line 133, in execute
    cursor.execute(sql, params)
  File "/Users/xxx/myapp/see/env/lib/python3.7/site-packages/django/db/backends/utils.py", line 68, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "/Users/xxx/myapp/see/env/lib/python3.7/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "/Users/xxx/myapp/see/env/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "/Users/xxx/myapp/see/env/lib/python3.7/site-packages/django/db/utils.py", line 89, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/Users/xxx/myapp/see/env/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "/Users/xxx/myapp/see/env/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 71, in execute
    return self.cursor.execute(query, args)
  File "/Users/xxx/myapp/see/env/lib/python3.7/site-packages/MySQLdb/cursors.py", line 198, in execute
    res = self._query(query)
  File "/Users/xxx/myapp/see/env/lib/python3.7/site-packages/MySQLdb/cursors.py", line 306, in _query
    db.query(q)
  File "/Users/xxx/myapp/see/env/lib/python3.7/site-packages/MySQLdb/connections.py", line 217, in query
    _mysql.connection.query(self, query)
django.db.utils.IntegrityError: (1215, 'Cannot add foreign key constraint')

Обновление: найдена первопричина

  1. Некоторые файлы миграции были удалены мной.Начиная с https://github.com/django/django/blob/2bd8df243ac6fc35e58c9fe90b20c9e42519a5ac/django/core/management/commands/migrate.py#L144, и меня, отслеживающего код Django с использованием ipdb, plan = executor.migration_plan(targets) возвращает текущие файлы / myapp / migrations / xxx вместо полной новой миграции с модели.
  2. Некоторые из моих моделейесть class Meta: managed = False.Вначале я управлял ими вручную, но я должен был изменить их на managed = True после первоначальной настройки, и все заработало.
  3. Исправление: локальное удаление всей базы данных (у меня есть резервная копия prod db), обновлениекод для managed: True для таблиц, создание пустой базы данных, makemigration, migrate (введите некоторое значение по умолчанию для столбцов, не допускающих значения NULL. Готово. Исправлено.
...