15. Django connecting to Mysql

  1. Installation PyMySQL, open cmd, pip install PyMySQL
  2. / In ... / Blog the init under .py directory to add:
import pymysql
pymysql.install_as_MySQLdb() 

3. Open a file settings.py, bold comment code, add database configuration code as follows:

# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases

# DATABASES = {
#     'default': {
#         'ENGINE': 'django.db.backends.sqlite3',
#         'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
#     }
# }

# 新增代码
DATABASES = {
    'default':{
        'ENGINE': 'django.db.backends.mysql',
        'HOST': '127.0.0.1',
        'PORT': '3306',
        'NAME': 'blog',
        'USER': 'root',
        'PASSWORD': '',
        'OPTIONS': {
            'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
        },
    }
}

4. Database Migration:

python manage.py makemigrations 
python manage.py migrate 
  1. Results as shown below:

Guess you like

Origin www.cnblogs.com/suim1218/p/11009594.html