Django Model Sync Table

淺唱寂寞╮ 提交于 2019-12-04 08:43:37

问题


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?


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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:

  • Migratory
  • simplemigrations



回答5:


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



来源:https://stackoverflow.com/questions/1115238/django-model-sync-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!