Django支援多種資料庫,sqlite,mysql,oracle等,其預設資料庫是sqlite
在settings檔案中可以發現:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
其預設資料庫是sqlite3
要想使用其他資料庫,需要修改相應的引擎和配置
(1)sqlite:
'ENGINE': 'django.db.backends.sqlite3', #設定引擎
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), #設定資料庫存放路徑
(2)mysql
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', #資料庫引擎設定
'NAME': 'test', #資料庫名稱
'USER': 'root', #資料庫使用者名
'PASSWORD':'root', #資料庫密碼
'HOST':'', #主機位址,預設localhost
'PORT':'3306' #資料庫端口
}
}
然後在APP目錄下models檔案中添加:
from django.db import models
# Create your models here.
class UserInfo(models.Model):
username = models.CharField(max_length=64)
age = models.IntegerField()
使用指令生成資料表(python---django使用資料庫(orm)):
python manage.py makemigrations
python manage.py migrate
會發現報錯:
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb
原因是因為:
Django預設你導入的是MySQLdb,但是MySQLdb 對于py3版本有很大問題,是以我們需要的驅動為pymysql,是以在項目名檔案夾的__init__.py中引入pymysql(也可以直接在settings下的全局檔案__init__.py中引入)
import pymysql
pymysql.install_as_MySQLdb()
再進行啟動,可以成功建立。
轉載于:https://www.cnblogs.com/ssyfj/p/8645894.html