Django - Integrity error: Foreign Key constraint failed

Sumedha Gn
Apr 2, 2021

The Django version I am using 3.1.7 and SQLite. I encountered this issue although I was not using any foreign key constraints in my models.py. So this should stem from a migration issue and the database not syncing properly.

Solution

Delete/Drop the whole database and redo the migrations

  1. Delete db.sqlite3 file
  2. In the migrations folders of all django apps of your project, delete all files (e.g. 001_initial.py) and pycache folder, except for init.py
  3. Edit your models.py if needed
  4. Run python manage.py makemigrations or python3 manage.py makemigrations
  5. Then run python manage.py migrate or python3 manage.py migrate

Hope this helps. Happy coding!

--

--

Sumedha Gn

Documenting errors I’ve faced so you can save time trying to resolve them, feel free to let me know how I can improve too!