Django鏈接MySQL數據庫

CREATE DATABASE 'mysite' DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;python

在myslq中建立mysite數據庫mysql

 

修改應用polls包裏面的models.pysql

from django.db import models

# Create your models here.
# 在咱們的polls應用程序中,
# 將建立兩個模型:Question和Choice,
# Question有一個問題和一個出版日期,
# Choice有兩個領域:選擇的文本和票數,
# 每一個Choice都關聯一個Question


class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('出版日期')


class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)

 

修改項目mysite包裏面的settings.py數據庫

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mysite',
'HOST': '192.168.1.138',
'PORT': '3306',
'USER': 'root',
'PASSWORD': 'Abcdef@123456',
}
}
# 鏈接MySQL數據庫

 

修改項目mysite包裏面的初始化文件__init__.pydjango

import pymysql

pymysql.install_as_MySQLdb()

(請注意是項目的__init__.py,而不是應用的__init__.py)ui

 

python manage.py makemigrationsspa

運行makemigrations激活模型code


python manage.py migrateblog

再次運行migrate以在數據庫中建立這些模型表ci

 

進行模型更改的三步曲:
一、改變你的模型
二、運行覺得這些更改建立遷移(python manage.py makemigrations
三、運行以將這些更改應用於數據庫(python manage.py migrate

 

 

有坑的地方:

一、若是報錯File "/lib/site-packages/django/db/backends/mysql/base.py", line 36, in <module>
    raise ImproperlyConfigured('mysqlclient 1.3.13 or newer is required; you have %s.' % Database.__version__)
django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3.

/python3.6/site-packages/django/db/backends/mysql/base.py文件第35~36行註釋掉

 

 二、若是報錯File "/lib/site-packages/django/db/backends/mysql/operations.py", line 146, in last_executed_query
    query = query.decode(errors='replace')
AttributeError: 'str' object has no attribute 'decode'

/python3.6/site-packages/django/db/backends/mysql/operations.py文件第145~146行註釋掉

相關文章
相關標籤/搜索