Django - view sql query without publishing migrations
DjangoDjango Problem Overview
When I make changes to some models, I want to view the SQL the django would be running to implement those changes on the DB.
The normal way of doing this would be to do 'makemigrations appname'. This will generate a migration, let's say, - '0001_someName.py'. Then one can do 'sqlmigrate 0001_someName.py'
But I want to view the sql directly, without having to create that intermediate migration. Can this be done?
Django Solutions
Solution 1 - Django
Use the sqlmigrate
command from manage.py
.
python manage.py sqlmigrate <appname> <migration number eg. 0001 or 0004>
will display the SQL statements for a specific migration of the app.
Solution 2 - Django
Django does not provide that option. You can always create the migration, run sqlmigrate
, and delete the migration file. As long as it isn't applied with migrate
, nothing will happen.
Solution 3 - Django
Run
python manage.py sql <appname>
-- Prints the CREATE TABLE SQL statements for the given app name(s).
python manage.py sqlall <appname>
-- Prints the CREATE TABLE and initial-data SQL statements for the given app name(s).
You'll find detail documentation here. https://docs.djangoproject.com/en/1.8/ref/django-admin/
Solution 4 - Django
These existing answers are not enough, as I found out trying to follow them. First detect and make the migration script for your app:
manage.py makemigrations app
Make note of the four-digit migration number which starts the filename. Then print the SQL with:
manage.py sqlmigrate app 0002 # <-- number here
When finished, remove the file before it gets run or committed:
rm api/migrations/0002_auto_8675309.py