Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django 2.0: sqlite IntegrityError: FOREIGN KEY constraint failed

I'm working on adding Django 2.0 support to the django-pagetree library. During automated testing, using an sqlite in-memory database, I'm getting a bunch of errors like this:

  File "/home/nnyby/src/django-pagetree/pagetree/tests/test_models.py", line 638, in setUp
    'children': [],
  File "/home/nnyby/src/django-pagetree/pagetree/models.py", line 586, in add_child_section_from_dict

...

  File "/home/nnyby/src/django-pagetree/venv/lib/python3.5/site-packages/django/db/backends/base/base.py", line 239, in _commit
    return self.connection.commit()
django.db.utils.IntegrityError: FOREIGN KEY constraint failed

This is noted in the Django 2.0 release notes: https://docs.djangoproject.com/en/2.0/releases/2.0/#foreign-key-constraints-are-now-enabled-on-sqlite

From that description, which I don't fully understand, this shouldn't apply for test databases that aren't persistent, right? Wouldn't my sqlite test db get created with the appropriate options when using Django 2.0?

The app settings I'm using for testing are here: https://github.com/ccnmtl/django-pagetree/blob/master/runtests.py

like image 214
nnyby Avatar asked Dec 03 '17 16:12

nnyby


People also ask

How do I fix foreign key constraint failure?

The error message itself showing there is a foreign key constraint error, which means you are deleting a parent table where the child table contains the Primary table identifier as a foreign key. To avoid this error, you need to delete child table records first and after that the parent table record.

What is integrity error in Django?

This means that your DB is expecting that field to have a value. So when it doesn't you get an error. null. If True, Django will store empty values as NULL in the database. Default is False.


1 Answers

In my case, i found that the ForeignKey object that my model refer to is not exist. So that i just change the referenced FK object to exist object.

like image 192
Lê Hoàng Vũ Avatar answered Sep 24 '22 07:09

Lê Hoàng Vũ