Search code examples
pythonmysqldjangodatabasedjango-south

Django: create database tables programmatically/dynamically


I've been working on a Django app for some time now and have encountered a need for dynamic model and database table generation. I've searched far and wide and it seems as though the Django API does not include this function. From what I have gathered, South has a function to do this (i.e. south.db.create_table). However, from what I have gathered from South's release notes, South is not compatible with Django 1.7 and higher and my project was built using Django 1.9.

I have already written a script that creates model instances of the schema I would like to migrate to my database using the following method:

attrs = {'__module__':model_location, 'Meta':Meta}
model = type(table_name, (models.Model,), attrs)

p.s. please note that this is not the entirety of the mentioned script. If you think this would be useful for me to provide I can add it upon request.

Has anyone found a workaround for using South 1.0.2 with Django 1.9? If not does anyone have any ideas on how I could achieve this functionality without South? I have tried to think of alternative methods (rather than dynamically generating tables) but this really seems like it would provide the most concise and clean results given the scope of my project.

Thank you!


Solution

  • The reason South is incompatible with recent Django versions is that it has been rolled into Django as of Django 1.7, under the name "migrations". If you are looking for similar functionality the starting point would be the documentation on migrations. In particular you may be interested in the section on RunSQL.

    If you wish to avoid the migrations module you can also perform raw SQL queries.