django1.9 实现模型变更三步走

django与数据库同步,Django_book_2中提到python manage.py syncdb即可。本人下载django版本为1.9.7:

tust@tust:~$ python
Python 2.7.6 (default, Mar 22 2014, 22:59:38) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> django.VERSION
(1, 9, 7, 'final', 0)

执行此命令提示没有次命令:

tust@tust:~/djcode/mysite$ python manage.py syncdb
Unknown command: 'syncdb'
Type 'manage.py help' for usage.


查看Django中文文档, 内容如下:

实现模型变更的三个步骤:

    修改你的模型(在models.py文件中)。
    运行python manage.py makemigrations ,为这些修改创建迁移文件
    运行python manage.py migrate ,将这些改变更新到数据库中。

实测如下:(自建app模块名称为books,建好model后)

1.生成漂移文件。

tust@tust:~/djcode/mysite$ python manage.py makemigrations books
Migrations for 'books':
  0001_initial.py:
    - Create model Author
    - Create model Book
    - Create model Publisher
    - Add field publisher to book
2.同步到数据库
tust@tust:~/djcode/mysite$ python manage.py migrate
Operations to perform:
  Apply all migrations: admin, contenttypes, books, auth, sessions
Running migrations:
  Rendering model states... DONE
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying books.0001_initial... OK
  Applying sessions.0001_initial... OK


       查看相应数据库,发现已将模型同步到数据库,具体数据库内容不再赘述。

另注:

        可用一下命令查看漂移文件对应的sql脚本( python manage.py sqlmigrate  + app_name + 漂移文件)

python manage.py sqlmigrate books  0001
        其中,sqlmigrate命令并不会在你的数据库上真正运行迁移文件 —— 它只是把Django 认为需要的SQL打印在屏幕上以让你能够看到。 这对于检查Django将要进行的数据库操作或者你的数据库管理员需要这些SQL脚本是非常有用的。


猜你喜欢

转载自blog.csdn.net/tustzhoujian/article/details/51984655