Monthly Archives: December 2014

Generating raw SQL query for Django model definition to create table schema manually


I was working on an existing Django project (with an old version) and needed to modify some of existing models to add some new fields in the table (including some many to many fields). Definitely is the right way to deal such schema and data migrations, however this was not the option for me due to some constraints.

Following is one of the sample model, I had in my project:

According to the Django 1.7 release note , Django now has built-in support for schema migrations. It allows models to be updated, changed, and deleted by creating migration files that represent the model changes and which can be run on any development, staging or production database. Again, this was of no use for me as I was working with a legacy system :(.

I was left with only one option, somehow I needed the raw SQL query which Django fires on database while creating a table in database. Looking into the python doc, I got what I needed. Django has a command which generates the raw SQL for the provided application, which works in the following way:

python sql business

Here, business was my Django application under my project. Hope it helps!!