Ariel
Ariel

Reputation: 3611

How to see SQL query that caused error in Django migration?

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.

Upvotes: 11

Views: 3432

Answers (2)

Devang Padhiyar
Devang Padhiyar

Reputation: 3697

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.

Upvotes: 9

BlackBoxSql
BlackBoxSql

Reputation: 66

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

Upvotes: 0

Related Questions