Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Model Sync Table

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?

like image 453
geowa4 Avatar asked Dec 07 '22 06:12

geowa4


2 Answers

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.

like image 198
SingleNegationElimination Avatar answered Dec 11 '22 09:12

SingleNegationElimination


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.

like image 38
Sam Avatar answered Dec 11 '22 11:12

Sam