Django 1.7使用Migrations将模型应用到数据库

作者: youngsend
发布时间:2015-07-29 11:33:19

Django 1.7用Migrations替换了更早Django版本的将模型应用到数据库的方式(syncdb),原因是syncdb只能用来向数据库里添加新的模型,但不能修改或删除数据库里已有的模型。由于djangobook这个优质的中译DjanGo教程里使用的是老的应用模型方式,因而单提出来。

模型简单说来就是我们在Django定义的数据对象的结构(比如一个Book类就是一个Model)。将模型应用到数据库,就是让数据库依据我们定义的数据对象来建表,和表的关系。

仍以djangobook模型里所举的books这个app为例。只要你用的是Django 1.7版本,在books中就会自动生成migrates这个文件夹。Django就是依据migrates这个文件夹来将模型应用到数据库。

在books的models.py中新建好三个模型Author, Book, Publisher之后,先为books应用创建一个新的migrates,其实就是修改migrates文件夹里的文件

python manage.py makemigrations

会显示:

Migrations for 'books':
    0001_initial.py:
        - Create model Author
        - Create model Book
        - Create model Publisher
        - Add field publisher to book

接着,将migrates文件夹应用到数据库中,即在数据库中建表

python manage.py migrate

会显示:

Operations to perform:
    Apply all migrations: books
Running migrations:
    Applying books.0001_initial... OK

看看数据库中是不是建好表了,打开MySQL的shell:

mysql -u root -p

python manage.py dbshell

假设books应用所在project的数据库名是django_db,输入

SHOW TABLES IN django_db;

会显示五个表:

books_author
books_book
books_book_authors
books_publisher
django_migrations

说明模型应用成功。books_book_authors这个表是因为,我们在Book这个类里使用了authors属性,并为Author和Book设置了多对多的关系类型。

之后,每次你修改了models.py里的Model们,只要先用makemigrations命令覆盖migrations文件夹,再用migrate命令使改动被应用到数据库中。

但如果你是修改project里的settings.py中的INSTALLED_APPS和MIDDLEWARE_CLASSES,那么只需要执行migrate命令。


Python之禅(The Zen of Python, by Tim Peters, import this)

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren’t special enough to break the rules.
Although practicality beats purity.

Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one– and preferably only one –obvious way to do it.
Although that way may not be obvious at first unless you’re Dutch.

Now is better than never.
Although never is often better than *right* now.

If the implementation is hard to explain, it’s a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea – let’s do more of those!


版权声明:本文为博主原创文章,未经博主允许不得转载。

标签: Django Go 数据库
来源:http://blog.csdn.net/youngsend/article/details/44706713

推荐: