Django:更改模型而不清除所有数据? [英] Django: Change models without clearing all data?

查看:101
本文介绍了Django:更改模型而不清除所有数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些我正在使用的新型Django安装模型。我可以在不丢失应用数据的情况下更改字段?



我尝试更改字段并运行 python manage.py syncdb 。没有此命令的输出。



重命名为管理页面以编辑更改的模型会导致TemplateSyntaxErrors,因为Django试图显示db中不存在的字段。 / p>

我正在使用SQLite。



我可以删除数据库文件,然后重新运行 python manage.py syncdb ,但这是一种痛苦。有更好的方法吗?

解决方案

Django不会更改现有的数据库列。例如,Syncdb将创建表,但不会像Rails中那样做迁移。如果您需要这样的东西,请查看 Django South



请参阅合并文档


Syncdb不会更改现有表



syncdb只会为尚未安装的模型创建表。它将永远不会发出ALTER TABLE语句以匹配安装后对模型类所做的更改。对模型类和数据库模式的更改通常涉及某种形式的歧义,在这种情况下,Django将不得不猜测正确的变化。在这个过程中有一个关键数据丢失的风险。



如果您对模型进行了更改,并希望将数据库表更改为匹配,请使用sql命令来显示新的SQL结构,并将其与现有的表模式进行比较,以确定更改。


您必须更改列通过sqlite提供的任何管理工具手动输入数据库中的名称。例如,我已经用MySQL完成了,因为MySQL可以让您更改列名而不影响数据,这是没有问题的。


I have some models I'm working with in a new Django installation. Is it possible to change the fields without losing app data?

I tried changing the field and running python manage.py syncdb. There was no output from this command.

Renavigating to admin pages for editing the changed models caused TemplateSyntaxErrors as Django sought to display fields that didn't exist in the db.

I am using SQLite.

I am able to delete the db file, then re-run python manage.py syncdb, but that is kind of a pain. Is there a better way to do it?

解决方案

Django does not ever alter an existing database column. Syncdb will create tables, but it does not do 'migrations' as found in Rails, for instance. If you need something like that, check out Django South.

See the docs for syndb:

Syncdb will not alter existing tables

syncdb will only create tables for models which have not yet been installed. It will never issue ALTER TABLE statements to match changes made to a model class after installation. Changes to model classes and database schemas often involve some form of ambiguity and, in those cases, Django would have to guess at the correct changes to make. There is a risk that critical data would be lost in the process.

If you have made changes to a model and wish to alter the database tables to match, use the sql command to display the new SQL structure and compare that to your existing table schema to work out the changes.

You have to change the column names in your DB manually through whatever administration tools sqlite provides. I've done this with MySQL, for instance, and since MySQL lets you change column names without affecting your data, it's no problem.

这篇关于Django:更改模型而不清除所有数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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