/ Django

配置Django数据库为MySQL

开发环境:
  Python: 3.6.5
  Django: 2.05

Django默认自带的开发数据库是SQLite,我们也可以更换成其他的数据库,如MySQL。在Python3版本能用的MySQL驱动mysqlclient和pymysql。但mysqlclient在MacOS下安装报错("ld: library not found for -lssl"),索性使用pymysql。这是由纯python编写的客户端驱动库。如果需要更改数据库为MySQL,如下设置即可

  1. 安装pymysql
$ pip install pymysql
Collecting pymysql
  Downloading https://files.pythonhosted.org/packages/32/e8/222d9e1c7821f935d6dba8d4c60b9985124149b35a9f93a84f0b98afc219/PyMySQL-0.8.1-py2.py3-none-any.whl (81kB)
    100% |████████████████████████████████| 81kB 260kB/s
Installing collected packages: pymysql
Successfully installed pymysql-0.8.1
  1. 更改settings.py的数据库字段如下:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'dbname',
        'USER': 'root',
        'PASSWORD': 'password',
        'HOST': '127.0.0.1',
        'PORT': '3306',
    }
}
  1. 并在项目下__init__.py初始设置:
import pymysql
pymysql.install_as_MySQLdb()
  1. 初始化数据库
$ python manage.py migrate
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 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 sessions.0001_initial... OK

更多参考

  1. PyMySQL:https://github.com/PyMySQL/PyMySQL
  2. Settings:database
配置Django数据库为MySQL
Share this