django:更新数据库架构而不丢失数据 [英] django: update database schema without losing data

查看:260
本文介绍了django:更新数据库架构而不丢失数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想升级(更改)我的数据库模式(通过将它们添加到django模型中,将新的字段添加到表中),而不会丢失这些表中的数据,那么最好的解决方案是什么? syncdb当然不添加它们,所以我需要你的建议如何更改表而不删除它们,并使用syncdb重新创建。

What is the best solution if I want to upgrade (alter) my database schema (add new fields to tables by adding them just to django models) without losing data in these tables? "syncdb" not adding them of course, so I need your advices how to alter tables without deleting them and recreating again with syncdb.

谢谢
Ignas

Thanks, Ignas

推荐答案

当南方不是一个选项时,我只需手动编写脚本进行小的更改。和大的我使用

When south isn't an option I just manually write scripts for small changes. and big ones i use

./manage.py dumpdata appname

http://docs.djangoproject.com/en/dev/ref/django-admin/#dumpdata-appname-appname-appname-model

将其投入到文件中。运行正则表达式替换以更新任何添加/删除的字段,然后可以重置该应用程序。我不得不承认我没有这样做,但是如果需要,我可以获得一些特定的代码来为你做这个。

Throw that into a file. Run a regex replace to update any added /removed fields and then a reset of that app is possible. I have to admit i haven't done this in a while but i can get some specific code to do this for you if needed.

它加载了 loaddata

编辑

单个模型的Django转储数据此问题类似,可能有我正在谈论的信息。

Django dump data for a single model? This Question is similar and might have the info i was talking about.

仍然让我知道,如果你需要,我会挖掘我的旧脚本(或写出一个很好的简单的一个)为你。

Still let me know if you need and i'll dig up my old script (or write out a nice simple one) for you.

更新

./manage.py dumpdata appname --indent=4 > appname.json

#open your fav text editor and do a find/replace 

./manage.py reset appname
./manage.py loaddata appname.json

应该这样做。当您找到替换时,只需要删除不再有的字段,并添加不为空的字段。 (至少)。

That should do it. When you do a find replace you only need to remove fields that you don't have any more and add fields that aren't nullable. (as a minimum).

注意: --indent = 4很好地为您设置所有内容。这意味着4个空格。
./manage.py重置只适用于django 1.3(gah!)在django 1.3中,您将必须执行 ./管理dbshel​​l drop table 。从命令 ./ manage.py sqlreset appname 中找到sql。

Notes: the --indent=4 nicely formats everything for you. It means 4 spaces. the ./manage.py reset only works in pre django 1.3 (gah!) in django 1.3 you will have to do a ./manage dbshell and drop table. The sql for that is found from command ./manage.py sqlreset appname.

这篇关于django:更新数据库架构而不丢失数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆