Django18初体验


1148 浏览 5 years, 11 months

2.3 第一次迁移

版权声明: 转载请注明出处 http://www.codingsoho.com/

第一次迁移 First Migration

执行迁移命令

(trydjango18) D:\virtualdir\trydjango18\src>python manage.py migrate

如果数据库没有配好直接运行migrate命令,会有报错: settings.DATABASES is improperly configured,

设置database

如果数据库还没有安装,推荐使用SQLite这个最快和简单的方式。SQLite非常快,广泛应用,存储为单个文件。
如果使用SQLite之外的数据库,如PostgreSQL,MySQL,Oracle,MSSQL,都需要在settings.py里面配置DATABASES。
添加 “ENGINE” 和 “NAME” 配置,例子中我们选用sqlite3,关于mysql的配置会有专门章节介绍

SQLite是最常用的选择,甚至如果没有大量同时写操作的情况下也可以部署。

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': r'db.sqlite3',                      # Or path to database file if using sqlite3.
        # The following settings are not used with sqlite3:
        'USER': '',
        'PASSWORD': '',
        'HOST': '',                      # Empty for localhost through domain sockets or '[127.0.0.1](127.0.0.1)' for localhost through TCP.
        'PORT': '',                      # Set to empty string for default.
    }
}

在Python里,单引号和双引号在处理上是没有差别的,但必须保证开闭处符号相同。
在文件夹名字前,我加了一个r,表示'raw’,不要进行字符转义。例如:\n通常表示换行,但是在'raw’字符串里,它代表两个字符\n。所以r仅用于dos文件系统,告诉python不要进行转义。

创建表

Database配置好了之后,再次运行migrate
老的django版本里,用syncdb命令。

(trydjango18) D:\virtualdir\trydjango18\src>python manage.py migrate

Operations to perform:
  Synchronize unmigrated apps: staticfiles, messages
  Apply all migrations: contenttypes, sites, auth, sessions
Synchronizing apps without migrations:
  Creating tables...
    Running deferred SQL...
  Installing custom SQL...
Running migrations:
  Rendering model states... DONE
  Applying contenttypes.0001_initial... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0001_initial... 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 sessions.0001_initial... OK
  Applying sites.0001_initial... OK

python manage.py syncdb从1.9开始会被删除掉

(trydjango18) D:\virtualdir\trydjango18\src>python manage.py syncdb

D:\virtualdir\trydjango18\lib\site-packages\django\core\management\commands\syncdb.py:24: RemovedInDjango19Warning: The syncdb command will be removed in Django 1.9
  warnings.warn("The syncdb command will be removed in Django 1.9", RemovedInDjango19Warning)

Operations to perform:
  Synchronize unmigrated apps: staticfiles, admindocs, messages
  Apply all migrations: admin, contenttypes, sites, auth, sessions
Synchronizing apps without migrations:
  Creating tables...
    Running deferred SQL...
  Installing custom SQL...
Running migrations:
  Rendering model states... DONE
  Applying admin.0001_initial... OK

指向完migrate命令之后,新的数据表更新到了数据库中。