一、创建项目和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’ } }

  1. - 在项目目录下的__init__.py文件中设置
  2. ```python
  3. import pymysql
  4. pymysql.version_info = (1, 4, 13, "final", 0)
  5. pymysql.install_as_MySQLdb()
  6. # 注意:需要先使用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即可,重新执行数据迁移

  1. - 给客户端返回数据时格式不是JSON类型报错
  2. ```shell
  3. TypeError: In order to allow non-dict objects to be serialized set the safe parameter to False.
  4. --解决办法
  5. 在返回数据的后边添加 safe=False
  6. # 例如
  7. class BookInfoView(View):
  8. def get(self, request, *args, **kwargs):
  9. """获取所有书籍"""
  10. books = BookInfo.objects.all()
  11. # 数据转换
  12. book_list = []
  13. for book in books:
  14. book_dict = {
  15. "id": book.id,
  16. "title": book.btitle,
  17. "pub_date": book.bpub_date,
  18. "read": book.bread,
  19. "comment": book.bcomment,
  20. "is_delete": book.is_delete
  21. }
  22. book_list.append(book_dict)
  23. return http.JsonResponse(book_list, safe=False)