10

I'm trying to run a data migration that deletes all rows in a table (say, MyModel). There is another table that points to that table (RelatedModel). The field in the RelatedModel that maps to MyModel has on_delete=models.SET_NULL. When I run the migration, however, I get:

  File "/usr/local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 211, in _commit
    return self.connection.commit()
IntegrityError: update or delete on table "MyModel" violates foreign key constraint "f2274d6f2be82bbff458f3e5487b1864" on table "RelatedModel"
DETAIL:  Key (uuid)=(ywKMUYx7G2RoK9vqqEWZPV) is still referenced from table "RelatedModel".

I added a breakpoint in the migration and checked the SQL DELETE queries. I ran them interactively in the shell and they worked inside the transaction, but the migration still breaks when it tries to commit it. I can't see however which query exactly causes this error, so I don't know how to debug this. Any suggestions? Thanks.

PS: I'm using Django 1.9.13, Python 2.7, PostgreSQL 10.4.

Ariel
  • 3,383
  • 4
  • 43
  • 58
  • Could you post the migration files (py) that are run during that migrate. Also the table expressions from the Postgresql would help. – Juho Rutila Dec 19 '18 at 12:56

2 Answers2

7

You can print SQL statements for particular migration by using following management command.

python manage.py sqlmigrate <app label> <migration_name to print sql for>

For an instance if you want to check migration for hello app in your django project and suppose you want to print sql statements for 0001_initial.py. Than you need to execute following line.

python manage.py sqlmigrate hello 0001_initial.py

It would print SQL definations (statements) that will be executed on migration.

Devang Padhiyar
  • 3,427
  • 2
  • 22
  • 42
  • 1
    I'm using Django 2.5 and this didn't work for me. I had to do the following: `python manage.py sqlmigrate hello 0001` – mustang Nov 14 '19 at 01:47
  • The name of the migrations has to be mentioned without the .py at the end. Django doesn't support this anymore. In case of your example the following line has to be executed. `python manage.py sqlmigrate hello 0001_initial` – Ahmed May 04 '20 at 19:59
1

Use django-debug-toolbar to see in details. OR TRY: 1.Make your models clear as you want. 2.Try deleting the migrations except for init file. 3.delete the db file. 4. now makemigrations to the app 5. then migrate