Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

python - update django database to reflect changes in existing models

I've already defined a model and created its associated database via manager.py syncdb. Now that I've added some fields to the model, I tried syncdb again, but no output appears. Upon trying to access these new fields from my templates, I get a "No Such Column" exception, leading me to believe that syncdb didn't actually update the database. What's the right command here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As of Django 1.7+, built-in migrations support, allows for database schema migrations that preserve data. That's probably a better approach than the solution below.

Another option, not requiring additional apps, is to use the built in manage.py functions to export your data, clear the database and restore the exported data.

The methods below will update the database tables for your app, but will completely destroy any data that existed in those tables. If the changes you made to your app model do not break your old schema (for instance, you added a new, optional field) you can simply dump the data before and reload it afterwards, like so:

Django 1.4.15 and earlier

python manage.py dumpdata <your_app> > temp_data.json
python manage.py reset <your_app>
python manage.py loaddata temp_data.json

Django 1.5 and newer

python manage.py dumpdata <your_app> > temp_data.json
python manage.py sqlclear <your_app> | python manage.py dbshell
python manage.py syncdb
python manage.py loaddata temp_data.json

(The reset command was deprecated and then removed in Django 1.5)

If your changes break your old schema this won't work - in which case tools like South or Django Evolution are great.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...