django.db.utils.IntegrityError: FOREIGN KEY constraint failed while executing LiveServerTestCases through Selenium and Python Django

落爺英雄遲暮 提交于 2019-12-05 17:46:09

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

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

As per Django 2.0 release notes:

  • 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)
    
  • If you don’t recreate the foreign key as DEFERRED, the first create() would fail as the foreign key constraints are enforced.

  • @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?
      
    • 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!