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

问题描述

我可以成功运行所有单元测试,如果运行独立服务器,甚至可以成功运行硒测试,但是当我尝试使用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:\Users\Win7\.virtualenvs\lang-QbOXb8q_\lib\site-packages\django\db\backends\base\base.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:\Users\Win7\.virtualenvs\lang-QbOXb8q_\lib\site-packages\django\test\testcases.py", line 209, in __call__
    self._post_teardown()
  File "C:\Users\Win7\.virtualenvs\lang-QbOXb8q_\lib\site-packages\django\test\testcases.py", line 908, in _post_teardown
    self._fixture_teardown()
  File "C:\Users\Win7\.virtualenvs\lang-QbOXb8q_\lib\site-packages\django\test\testcases.py", line 943, in _fixture_teardown
    inhibit_post_migrate=inhibit_post_migrate)
  File "C:\Users\Win7\.virtualenvs\lang-QbOXb8q_\lib\site-packages\django\core\management\__init__.py", line 148, in call_command
    return command.execute(*args, **defaults)
  File "C:\Users\Win7\.virtualenvs\lang-QbOXb8q_\lib\site-packages\django\core\management\base.py", line 353, in execute
    output = self.handle(*args, **options)
  File "C:\Users\Win7\.virtualenvs\lang-QbOXb8q_\lib\site-packages\django\core\management\commands\flush.py", line 80, in handle
    emit_post_migrate_signal(verbosity, interactive, database)
  File "C:\Users\Win7\.virtualenvs\lang-QbOXb8q_\lib\site-packages\django\core\management\sql.py", line 51, in emit_post_migrate_signal
    **kwargs
  File "C:\Users\Win7\.virtualenvs\lang-QbOXb8q_\lib\site-packages\django\dispatch\dispatcher.py", line 175, in send
    for receiver in self._live_receivers(sender)
  File "C:\Users\Win7\.virtualenvs\lang-QbOXb8q_\lib\site-packages\django\dispatch\dispatcher.py", line 175, in <listcomp>
    for receiver in self._live_receivers(sender)
  File "C:\Users\Win7\.virtualenvs\lang-QbOXb8q_\lib\site-packages\django\contrib\auth\management\__init__.py", line 79, in create_permissions
    Permission.objects.using(using).bulk_create(perms)
  File "C:\Users\Win7\.virtualenvs\lang-QbOXb8q_\lib\site-packages\django\db\models\query.py", line 471, in bulk_create
    obj_without_pk._state.db = self.db
  File "C:\Users\Win7\.virtualenvs\lang-QbOXb8q_\lib\site-packages\django\db\transaction.py", line 212, in __exit__
    connection.commit()
  File "C:\Users\Win7\.virtualenvs\lang-QbOXb8q_\lib\site-packages\django\db\backends\base\base.py", line 261, in commit
    self._commit()
  File "C:\Users\Win7\.virtualenvs\lang-QbOXb8q_\lib\site-packages\django\db\backends\base\base.py", line 239, in _commit
    return self.connection.commit()
  File "C:\Users\Win7\.virtualenvs\lang-QbOXb8q_\lib\site-packages\django\db\utils.py", line 89, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "C:\Users\Win7\.virtualenvs\lang-QbOXb8q_\lib\site-packages\django\db\backends\base\base.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 版本数据库 的更多信息类型版本以及您的代码试用将帮助我们更好地调试此问题.

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:\Users\Win7\.virtualenvs\lang-QbOXb8q_\lib\site-packages\django\core\management\sql.py", line 51, in emit_post_migrate_signal **kwargs
.
File "C:\Users\Win7\.virtualenvs\lang-QbOXb8q_\lib\site-packages\django\db\backends\base\base.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约束失败).
  • 外键现在使用可延期初始递延而不是可立即递延来创建.因此,可能需要重建表以使用新定义重新创建外键,尤其是如果您使用以下模式;

  • 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 constraint 错误而失败,因为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:通过Selenium和Python Django执行LiveServerTestCases时,FOREIGN KEY约束失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

  • 10-19 10:39