本文介绍了django.db.utils.IntegrityError: FOREIGN KEY 约束在通过 Selenium 和 Python Django 执行 LiveServerTestCases 时失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以成功运行所有单元测试,如果我运行独立服务器,我什至可以成功运行 selenium 测试,但是当我尝试使用 LiveServerTestCases 以独立的方式测试所有内容时,每个 LiveServerTestCase 测试都以以下错误结束完成tearDown函数后:

I can run all unit tests successfully, I can even run selenium tests successfully if I run an independent server, but when I try to use LiveServerTestCases to test everything in a self-contained manner, each LiveServerTestCase test ends with the following error after completing the tearDown function:

  File "C:UsersWin7.virtualenvslang-QbOXb8q_libsite-packagesdjangodbackendsasease.py", line 239, in _commit
    return self.connection.commit()
django.db.utils.IntegrityError: FOREIGN KEY constraint failed

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

Traceback (most recent call last):
  File "C:UsersWin7.virtualenvslang-QbOXb8q_libsite-packagesdjango	est	estcases.py", line 209, in __call__
    self._post_teardown()
  File "C:UsersWin7.virtualenvslang-QbOXb8q_libsite-packagesdjango	est	estcases.py", line 908, in _post_teardown
    self._fixture_teardown()
  File "C:UsersWin7.virtualenvslang-QbOXb8q_libsite-packagesdjango	est	estcases.py", line 943, in _fixture_teardown
    inhibit_post_migrate=inhibit_post_migrate)
  File "C:UsersWin7.virtualenvslang-QbOXb8q_libsite-packagesdjangocoremanagement\__init__.py", line 148, in call_command
    return command.execute(*args, **defaults)
  File "C:UsersWin7.virtualenvslang-QbOXb8q_libsite-packagesdjangocoremanagementase.py", line 353, in execute
    output = self.handle(*args, **options)
  File "C:UsersWin7.virtualenvslang-QbOXb8q_libsite-packagesdjangocoremanagementcommandsflush.py", line 80, in handle
    emit_post_migrate_signal(verbosity, interactive, database)
  File "C:UsersWin7.virtualenvslang-QbOXb8q_libsite-packagesdjangocoremanagementsql.py", line 51, in emit_post_migrate_signal
    **kwargs
  File "C:UsersWin7.virtualenvslang-QbOXb8q_libsite-packagesdjangodispatchdispatcher.py", line 175, in send
    for receiver in self._live_receivers(sender)
  File "C:UsersWin7.virtualenvslang-QbOXb8q_libsite-packagesdjangodispatchdispatcher.py", line 175, in <listcomp>
    for receiver in self._live_receivers(sender)
  File "C:UsersWin7.virtualenvslang-QbOXb8q_libsite-packagesdjangocontribauthmanagement\__init__.py", line 79, in create_permissions
    Permission.objects.using(using).bulk_create(perms)
  File "C:UsersWin7.virtualenvslang-QbOXb8q_libsite-packagesdjangodbmodelsquery.py", line 471, in bulk_create
    obj_without_pk._state.db = self.db
  File "C:UsersWin7.virtualenvslang-QbOXb8q_libsite-packagesdjangodb	ransaction.py", line 212, in __exit__
    connection.commit()
  File "C:UsersWin7.virtualenvslang-QbOXb8q_libsite-packagesdjangodbackendsasease.py", line 261, in commit
    self._commit()
  File "C:UsersWin7.virtualenvslang-QbOXb8q_libsite-packagesdjangodbackendsasease.py", line 239, in _commit
    return self.connection.commit()
  File "C:UsersWin7.virtualenvslang-QbOXb8q_libsite-packagesdjangodbutils.py", line 89, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "C:UsersWin7.virtualenvslang-QbOXb8q_libsite-packagesdjangodbackendsasease.py", line 239, in _commit
    return self.connection.commit()
django.db.utils.IntegrityError: FOREIGN KEY constraint failed

我很确定我的数据库模型中没有任何错误,因为当我启动一个单独的服务器实例并行运行时,所有单元测试都运行良好,硒测试运行良好,所以我猜测它与硒有关?

I'm pretty sure I don't have any errors in my database models, as all the unit tests run fine and the selenium tests run fine when I fire up a seperate server instance to run in parallel, so I'm guessing it has to do with selenium?

我尝试过使用 Chrome 网络驱动程序、IE 网络驱动程序和 Firefox 网络驱动程序.结果相同.它似乎与我的数据库无关,因为该错误仅发生在 LiveServerTestCases 上.

I've tried using the Chrome webdriver, IE webdriver and Firefox webdriver. Same results.It doesn't appear to be related to my database as the error only occurs for LiveServerTestCases.

  • Django 2.1 版
  • SQLite3 版本 3.20.0

推荐答案

关于 Django 版本数据库 的更多信息typeversion 以及您的 代码试验 将有助于我们以更好的方式调试此问题.

Some more information regarding the Django version, Database type and version along with your code trials would have helped us to debug this issue in a better way.

但是,这个错误信息...

However, this error message...

File "C:UsersWin7.virtualenvslang-QbOXb8q_libsite-packagesdjangocoremanagementsql.py", line 51, in emit_post_migrate_signal **kwargs
.
File "C:UsersWin7.virtualenvslang-QbOXb8q_libsite-packagesdjangodbackendsasease.py", line 239, in _commit
    return self.connection.commit()
django.db.utils.IntegrityError: FOREIGN KEY constraint failed

...暗示在尝试保存现有模型实例时引发了 IntegrityError.

...implies that an IntegrityError was raised while attempting to save an existing model instance.

根据 Django 2.0 发行说明:

  • 现在在 SQLite 上启用了外键约束:如果尝试保存违反外键约束的现有模型实例,这是一个向后不兼容的更改(IntegrityError: FOREIGN KEY 约束失败).
  • 现在使用 DEFERRABLE INITIALLY DEFERRED 而不是 DEFERRABLE IMMEDIATE 创建外键.因此,可能需要重建表以使用新定义重新创建外键,特别是如果您使用如下模式;

  • Foreign key constraints are now enabled on SQLite: This was a backwards-incompatible change (IntegrityError: FOREIGN KEY constraint failed) if attempting to save an existing model instance that’s violating a foreign key constraint.
  • Foreign Keys are now created with DEFERRABLE INITIALLY DEFERRED instead of DEFERRABLE IMMEDIATE. So the tables may need to be rebuilt to recreate foreign keys with the new definition, particularly if you’re using a pattern as follows;

from django.db import transaction

with transaction.atomic():
    Book.objects.create(author_id=1)
    Author.objects.create(id=1)

  • 如果您不将外键重新创建为 DEFERRED,第一个 create() 将作为外键失败强制执行约束.

  • If you don’t recreate the foreign key as DEFERRED, the first create() would fail as the foreign key constraints are enforced.

    @dirkgroten 在此讨论 举个例子:

    @dirkgroten in this discussion provided an example as follows:

    • 在你的代码中寻找这样的模式:

    • Look for patterns like this in your code:

     # in pagetree/models.py, line 810
     @classmethod
     def create_from_dict(cls, d):
        return cls.objects.create()  # what happens to d by the way?
    

  • 这肯定会因 ForeignKey 约束 错误而失败,因为 PageBlock 必须有部分,所以你不能在没有先分配它的情况下调用 create.

  • This will definitely fail with a ForeignKey constraint error since a PageBlock must have section, so you can't call create without first assigning it.

    这篇关于django.db.utils.IntegrityError: FOREIGN KEY 约束在通过 Selenium 和 Python Django 执行 LiveServerTestCases 时失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

  • 10-19 10:39