sqlupdate, creates sql to update the database based on an updated model file
|Reported by:||Owned by:||Adrian Holovaty|
|Component:||Database layer (models, ORM)||Version:||0.91|
|Has patch:||no||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
I've created a function for django-admin.py that dumps the sql that will transition an old database model (the one that is in the database currently) to a new one based an updated django model. So if you change the name of a model, or add a column, or delete a column, etc. it will output the sql to alter the database for you. And I think it's a shame that no one else has this, as it is remarkably usefull.
For instance, if I have this originally:
class Poll(meta.Model): question = meta.CharField(maxlength=128) responses = meta.IntegerField(default=0)
And I want to go to this:
class Poll(meta.Model): question = meta.CharField(maxlength=128) title = meta.CharField(maxlength=128)
It will create the sql to drop "responses" and add "title".
There are two steps in doing this. The first is to create a "transition" file. This file allows you to tweak the changes that the code thinks should be done. For instance, if you change Poll a lot, and then changed the name to Survey or something, it might think you dropped Poll and created a table called Survey. So it would create in the file:
But you might want to change it to:
Name("app_polls", "Survey") Change("Survey")
Which tells it that the table that was named polls, should be called "Survey" now, and also it should make all the changes to "Survey".
This all goes in a file right next to your model file. If your model file was called "model.py", the transition file would be called "model.transition.py"
The next step is to actually run the sqlupdate, that will analyze the transition file, and spew out the SQL to realize those changes.
To perform the complete steps:
- django-admin.py transition <app_name>
- <check the transition file to make sure it's kosher>
- django-admin.py sqlupdate <app_name> # which won't commit the changes
- django-admin.py sqlupdate <app_name> | mysql -p <project_name> # which will commit the changes (in mysql)