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行注释掉
来源:oschina
链接:https://my.oschina.net/u/4382879/blog/4024987