If I change a field in a Django model, how can I synchronize it with the database tables? Do I need to do it manually on the database or is there a tool that does helps with the process?
Alas, Django does not support any easy solution to this.
The only thing django will do for you, is restart your database with new tables that match your new models:
$ #DON'T DO THIS UNLESS YOU CAN AFFORD TO LOSE ALL YOUR DATA!
$ python PROJECT_DIR/manage.py syncdb
the next option is to use the various sql* options to manage.py to see what django would do to match the current models to the database, then issue your own ALTER TABLE
commands to make everything work right. Of course this is error prone and difficult.
The real solution is to use a database migration tool, such as south to generate migration code.
Here is a similar question with discussion about various database migration options for django.
Django Evolution can help, but the best option really is to plan out your schema in advance, or to make simple modifications manually. Or, to be willing to toast your test data by dropping tables and re-syncing.
Django does not provide for this out of the box.
Here's some information from the Django Book on doing it by hand (see Making Changes to a Database Schema). This works for straightforward, simple changes.
Longer-term, you'll probably want to use a migration tool. There are three major options:
- django-evolution
- Dmigrations (written by Simon Willison, one of the creators of Django) (works only with MySQL)
- South
EDIT: Looking through the question linked by TokenMacGuy, I'll add two more to the list for the sake of completeness:
Just to throw in an extra opinion - dmigrations is pretty nice and clear to use, but I'd say South is your best bet. Again, it's easy to get into, but it's more powerful and also has support for more database backends than just MySQL. It even handles MSSQL, if that's your thing
Can't seem to be able to add a comment to the marked answer, probably because I haven't got enough rep (be nice if SO told me so though).
Anyway, just wanted to add that in the answered post, I believe it is wrong about syncdb - syncdb does not touch tables once they have been created and have data in them. You should not lose data by calling it (otherwise, how could you add new tables for new apps?)
I believe the poster was referring to the reset command instead, which does result in data loss - it will drop the table and recreate it and hence it'll have all the latest model changes.