本文以 MySQL 数据库为例。
首先安装 mysqlclient,用于操作 MySQL 数据库:
pip install mysqlclient
接着,打开项目的 settings.py,修改数据库与时区配置:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'django',
'USER': 'django_user',
'PASSWORD': 'django_pwd',
'HOST': '127.0.0.1',
'PORT': '3306',
}
}
TIME_ZONE = 'Asia/Shanghai'
settings.py 配置文件默认使用 SQLite 数据库 。而且 Python 本身内置 SQLite, 所以无需额外安装就可以使用它。开始一个真实项目时,我们就会使用其它数据库,比如 MySQL,这时,就可以修改 DATABASES 的 ‘default’ 中的配置项。
ENGINE 可配置 Django 的数据库引擎。以下列出常用的数据库引擎:
数据库 | 引擎 |
---|---|
sqlite3 | django.db.backends.sqlite3 |
postgresql | django.db.backends.postgresql |
mysql | django.db.backends.mysql |
oracle | django.db.backends.oracle |
除了 ENGINE , DATABASES 的 ‘default’ 中还有以下这些配置项:
配置项 | 说明 |
---|---|
NAME | 数据库名称 |
USER | 账号 |
PASSWORD | 密码 |
HOST | IP地址 |
PORT | 端口号 |
还有一点,就是设置时区为中国所在时区,默认采用的是 UTC,即协调世界时,又称世界统一时间、世界标准时间、国际协调时间。由于英文(CUT)和法文(TUC)的缩写不同,作为妥协,简称 UTC。
settings.py 的 INSTALLED_APPS 事先定义好了这些应用:
应用 | 说明 |
---|---|
django.contrib.admin | 后台管理框架。 |
django.contrib.auth | 认证授权框架。 |
django.contrib.contenttypes | 内容类型框架。 |
django.contrib.sessions | 会话框架。 |
django.contrib.messages | 消息框架。 |
django.contrib.staticfiles | 静态文件管理框架。 |
执行以下命令,创建这些应用的相关基础表:
python manage.py migrate
运行结果:
System check identified some issues:
WARNINGS:
?: (mysql.W002) MySQL Strict Mode is not set for database connection ‘default’
HINT: MySQL’s Strict Mode fixes many data integrity problems in MySQL, such as data truncation upon insertion, by escalating warni
ngs into errors. It is strongly recommended you activate it. See: https://docs.djangoproject.com/en/3.0/ref/databases/#mysql-sql-mode
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial… OK
Applying auth.0001_initial… OK
Applying admin.0001_initial… OK
Applying admin.0002_logentry_remove_auto_add… OK
Applying admin.0003_logentry_add_action_flag_choices… 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 auth.0008_alter_user_username_max_length… OK
Applying auth.0009_alter_user_last_name_max_length… OK
Applying auth.0010_alter_group_name_max_length… OK
Applying auth.0011_update_proxy_permissions… OK
Applying sessions.0001_initial… OK
打开 Mysql 数据库,就可以看到相关基础表已经建好了: