Django - Integrity error: Foreign Key constraint failed
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
- Delete db.sqlite3 file
- 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
- Edit your models.py if needed
- Run
python manage.py makemigrations
orpython3 manage.py makemigrations
- Then run
python manage.py migrate
orpython3 manage.py migrate
Hope this helps. Happy coding!