Django测试“ django.db.utils.IntegrityError:(1215,'无法添加外键约束')”

时间:2019-02-22 01:45:47

标签: django django-2.1

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中尚未创建'assess_perspectives'表。我想知道,Django在测试运行期间如何决定表创建的顺序?这是Django错误,还是我使用的方式不正确?有什么方法可以强制在测试中首先创建“ assessment_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开始,我使用ipdb跟踪Django代码,plan = executor.migration_plan(targets)返回当前 / myapp / migrations / xxx文件,而不是从模型进行全新的迁移。
  2. 我的某些模型有class Meta: managed = False。一开始我是手动管理它们,但是在初始设置和一切正常后,我应该将它们更改为managed = True
  3. 解决方法:在本地删除整个数据库(我有产品数据库备份),更新代码以为表添加managed: True,创建空数据库,makemigration,迁移(为不可为空的列填写一些默认值。完成) 。固定。

0 个答案:

没有答案