Django連接MySQL數據庫


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

在myslq中創建mysite數據庫

 

修改應用polls包里面的models.py

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__.py

import pymysql

pymysql.install_as_MySQLdb()

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

 

python manage.py makemigrations

運行makemigrations激活模型


python manage.py migrate

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

 

進行模型更改的三步曲:
1、改變你的模型
2、運行以為這些更改創建遷移(python manage.py makemigrations
3、運行以將這些更改應用於數據庫(python manage.py migrate

 

 

有坑的地方:

1、如果報錯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行注釋掉

 

 2、如果報錯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行注釋掉

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM