天天看点

Django使用数据库(Mariadb/Mysql)

Django默认使用SQLite作为数据库,配置文件在settings.py

让我们来看一下

"""
Django settings for test1 project.

Generated by 'django-admin startproject' using Django 2.1.4.

For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'm5e#rg35zpd6m+ms*(rv0prfw#(()suuily9jr((-9dlq5b(j1'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'test1.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')]
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'test1.wsgi.application'


# 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'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/

STATIC_URL = '/static/'           

我们可以看到其中的

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

就是默认的配置了,默认配置的SQLite数据库并不需要添加其它的东西

但是由于我们要使用Mysql/mariadb,所以我们要配置一些其他的东西,例如数据库地址、端口等

如何配置Mysql/Mariadb数据库

首先我们需要安装合适的database bindings,这里我们选择安装PyMySQL

打开设置

Django使用数据库(Mariadb/Mysql)

选择project

Django使用数据库(Mariadb/Mysql)

最上面我们可以选择使用本机安装的那个Python,点击右边的加号即可添加其它的包

点击+号,搜索pymysql,点击添加即可

Django使用数据库(Mariadb/Mysql)

安装成功示意

Django使用数据库(Mariadb/Mysql)

接下来我们要在外层的__init__.py文件中写入如下代码

import pymysql

pymysql.install_as_MySQLdb()           

最后配置settings.py中的DATABASES部分就可以了

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'test',
        'USER': 'root',
        'PASSWORD':'密码',
        'HOST':'localhost',
        'PORT':'3306',
    }
}           

各项配置解释

ENGINE

数据库引擎,可选项'django.db.backends.sqlite3','django.db.backends.postgresql','django.db.backends.mysql',或 

'django.db.backends.oracle'等

NAME

数据库的名字

USER

数据库用户名

PASSWORD

数据库密码

HOST

数据库地址

PORT

数据库端口

修改时间

Django默认使用的是UTC时间,如果不修改的话在之后的使用中可能会遇到一些问题,因此这里不要忘记修改一下时间

修改settings.py文件中的TIME_ZONE即可

TIME_ZONE = 'UTC'
改为
TIME_ZONE = 'Asia/Shanghai'           

测试数据库是否成功连接

进入外层目录也就是manage.py所在的目录,cmd命令行下执行以下命令

python manage.py migrate           

出现如下命令,并且查看数据库新建了一些表,说明配置是正确的

Django使用数据库(Mariadb/Mysql)
Django使用数据库(Mariadb/Mysql)

注:生成的表可能不一样这个与settings.py 文件和每个应用的数据库迁移文件有关