1、指定連接pymysql(python3.x)

配置_init_.py所在地址
- 先配置init.py
import pymysql
pymysql.install_as_MySQLdb()
#Django連接MySQL時(shí)默認(rèn)使用MySQLdb驅(qū)動(dòng),但MySQLdb不支持Python3,因此這里將MySQL驅(qū)動(dòng)設(shè)置為pymysql
2.配置連接mysql文件信息
- settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'django_demo', #你的數(shù)據(jù)庫(kù)名稱(chēng) ,這個(gè)庫(kù)需要已經(jīng)存在
'USER': 'root', #你的數(shù)據(jù)庫(kù)用戶(hù)名
'PASSWORD': '123456', #你的數(shù)據(jù)庫(kù)密碼
'HOST': '10.177.15.139', #你的數(shù)據(jù)庫(kù)主機(jī),留空默認(rèn)為localhost
'PORT': '3306', #你的數(shù)據(jù)庫(kù)端口
}
}
3. 在 django_demo\application\models.py里面寫(xiě)建表語(yǔ)句
from django.db import models
# Create your models here.
class UserInfo(models.Model):
id=models.AutoField(primary_key=True)
name=models.CharField(max_length=16,help_text=u'名字')
moblie=models.IntegerField()
password=models.CharField(max_length=24)
4.在終端執(zhí)行命令
1、生成遷移文件:
python manage.py makemigrations
2、生成數(shù)據(jù)庫(kù)表:
python manage.py migrate
** 注意**:在生成遷移文件時(shí)候可能會(huì)報(bào)錯(cuò):
django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3.
解決方案:
找到Python環(huán)境下 django包的base.py文件,路徑如下:
python3.6/site-packages/django/db/backends/mysql/base.py
注釋base.py 中如下部分(35/36行)
# 注釋以下兩行代碼;解決 :django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3.
# if version < (1, 3, 13):
# raise ImproperlyConfigured('mysqlclient 1.3.13 or newer is required; you have %s.' % Database.__version__)
- 如果報(bào)錯(cuò):
AttributeError: ‘str’ object has no attribute ‘decode’
找到:site-packages\django\db\backends\mysql\operations.py文件(46行)
將decode改為encode,如下:
# 執(zhí)行django_demo>python manage.py makemigrations 時(shí)候報(bào)錯(cuò):AttributeError: 'str' object has no attribute 'decode'
# 解決錯(cuò)誤:
# if query is not None:
# query = query.decode(errors='replace')
# return query
if query is not None:
query = query.encode(errors='replace')
return query
再執(zhí)行第四步就不會(huì)報(bào)錯(cuò)了