Django模型同步表[英] Django Model Sync Table

本文是小编为大家收集整理的关于Django模型同步表的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

如果我更改Django模型中的字段,如何将其与数据库表同步?我需要在数据库上手动进行操作,还是有一个工具可以帮助该过程?

推荐答案

a,django不支持任何简单的解决方案.

Django唯一为您做的事情是,将数据库重新启动您的数据库,与您的新模型相匹配:

$ #DON'T DO THIS UNLESS YOU CAN AFFORD TO LOSE ALL YOUR DATA!
$ python PROJECT_DIR/manage.py syncdb

下一个选项是使用各种sql*选项来管理.当然,这很容易出错.

真正的解决方案是使用数据库迁移工具,例如 south 生成迁移代码.<<<<<<<<<<<<<<<<<<<<<<<

这是类似的问题讨论了Django的各种数据库迁移选项.

其他推荐答案

似乎无法在标记的答案中添加评论,这可能是因为我没有足够的代表(如果这样告诉我,那就好了).

).

无论如何,只想在回答的帖子中添加,我相信SynCDB -SynCDB do 触摸表一旦创建并在其中包含数据就错了.您应该通过调用而不是丢失数据(否则,如何添加新应用的新表?)

我相信海报是指重置命令,确实会导致数据丢失 - 它将放弃表并重新创建它,因此它将具有所有最新的模型更改.<<<<<<<<./p>

其他推荐答案

django Evolution 可以提供帮助,但最好的选择确实是提前计划模式,或者手动进行简单的修改.或者,愿意通过丢弃表并重新同步来敬酒您的测试数据.

本文地址:https://www.itbaoku.cn/post/597686.html

问题描述

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?

推荐答案

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.

其他推荐答案

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.

其他推荐答案

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.