一、创建项目和app
- 项目:django-admin startproject 项目名
- app :python3 manage.py startapp app名
启动服务:python3 manage.py runserver 端口号,默认为8000,可以省略
二、数据库设置
下载mysqlclient:pip3 install pymysql
- 基本设置 ```shell
DATABASES = { ‘default’: { ‘ENGINE’: ‘django.db.backends.mysql’, ‘HOST’: ‘127.0.0.1’, ‘PORT’: ‘3306’, ‘USER’: ‘root’, ‘PASSWORD’: ‘liqh930215’, ‘NAME’: ‘test1’ } }
- 在项目目录下的__init__.py文件中设置
```python
import pymysql
pymysql.version_info = (1, 4, 13, "final", 0)
pymysql.install_as_MySQLdb()
# 注意:需要先使用pip3引入pymysql
如果不指定版本运行程序可能会报错:django.core.exceptions.ImproperlyConfigured: mysqlclient 1.4.0 or newer is required; you have 0.10.1. ———> 解决办法:在init.py文件中的import pymysql后添加pymysql.version_info = (主版本号, 次版本号, 末尾版本号, “final”, 0),指定版本即可
- 生成迁移文件:python3 manage.py makemigrations
- 执行数据迁移:python3 manage.py migrate
- 常见问题:
- 问题一:数据迁移时出错 ```shell File “/Users/apple/workplace/test1/lib/python3.6/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’
—-解决办法 进入operations.py文件,找到query = query.decode(errors=’replace’)把decode改成encode即可,重新执行数据迁移
- 给客户端返回数据时格式不是JSON类型报错
```shell
TypeError: In order to allow non-dict objects to be serialized set the safe parameter to False.
--解决办法
在返回数据的后边添加 safe=False
# 例如
class BookInfoView(View):
def get(self, request, *args, **kwargs):
"""获取所有书籍"""
books = BookInfo.objects.all()
# 数据转换
book_list = []
for book in books:
book_dict = {
"id": book.id,
"title": book.btitle,
"pub_date": book.bpub_date,
"read": book.bread,
"comment": book.bcomment,
"is_delete": book.is_delete
}
book_list.append(book_dict)
return http.JsonResponse(book_list, safe=False)