#PPT
html
#Mysql使用python
mysql> create database HelloDjango charset=utf8; Query OK, 1 row affected (0.01 sec)
安装pymysql mysql
pip install pymysql -i https://pypi.douban.com/simple (venv) MacBookPro:HelloDjango zhangxm$ pip install pymysql Collecting pymysql Downloading https://files.pythonhosted.org/packages/ed/39/15045ae46f2a123019aa968dfcba0396c161c20f855f11dea6796bcaae95/PyMySQL-0.9.3-py2.py3-none-any.whl (47kB) |████████████████████████████████| 51kB 196kB/s Installing collected packages: pymysql Successfully installed pymysql-0.9.3 WARNING: You are using pip version 19.3.1; however, version 20.0.2 is available. You should consider upgrading via the 'pip install --upgrade pip' command.
安装上之后系统仍然是不认这个库的,pymysql假装成mysqlclient 比较经常使用的假装写在程序的__init__.py中git
import pymysql pymysql.install_as_MySQLdb()
###Django - installing mysqlclient error: mysqlclient 1.3.13 or newer is required; you have 0.9.3github
##解决方法 仍然使用pymysql 1 )配置文件的目录中_init_.py中有以下代码 import pymysql pymysql.install_as_MySQLdb() # 这是一个hack,为了在Djano中替代默认的mysqlclient。mysqlclient官方描述:This is a fork of MySQLdb1 2) 点进去install_as_MySQLdb 找到version_info变量,改为 version_info = (1, 3, 13, "final", 0) 3) 改变django.db.backends.mysql.operations.py的一行代码 query = query.decode(errors='replace') -> query = query.encode(errors='replace') 缘由:mysqlclient returns bytes object, PyMySQL returns str object 参考:https://github.com/PyMySQL/PyMySQL/issues/790#issuecomment-484201388
##python manage.py startapp Three 想要认可项目的存在,更改project settings文件:sql
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'App', 'Two', 'Three' # 'Three.apps.ThreeConfig' #1.9以后能够这样写 ]
而后写Three里的路由规则 ##新建urls.pyshell
from django.conf.urls import url from Three import views urlpatterns = [ url('^index/', views.index), ]
##views.pydjango
from django.http import HttpResponse from django.shortcuts import render # Create your views here. from django.template import loader def index(request): three_index = loader.get_template("three_index.html") context ={"student_name": '张三' } #有渲染,解析渲染引擎表达式的做用,若是不须要这些,直接open也能够 result = three_index.render(context=context) print(result) return HttpResponse(result)
##Three->>templates->>index.htmlsession
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Three_Index</title> </head> <body> <h2>Three Index</h2> {{ student_name }} </body> </html>
#定义模型 app
python shell
#关联(学生-班级) ##model.py
from django.db import models # Create your models here. class Grade(models.Model): g_name = models.CharField(max_length=32) class Student(models.Model): s_name = models.CharField(max_length=16) # django 升级到2.0以后,表与表之间关联的时候,必需要写on_delete参数,不然会报异常: # TypeError: init() missing 1 required positional argument: ‘on_delete’ s_grade = models.ForeignKey(Grade,on_delete=models.CASCADE) ''' on_delete=None, # 删除关联表中的数据时,当前表与其关联的field的行为 on_delete=models.CASCADE, # 删除关联数据,与之关联也删除 on_delete=models.DO_NOTHING, # 删除关联数据,什么也不作 on_delete=models.PROTECT, # 删除关联数据,引起错误ProtectedError # models.ForeignKey('关联表', on_delete=models.SET_NULL, blank=True, null=True) on_delete=models.SET_NULL, # 删除关联数据,与之关联的值设置为null(前提FK字段须要设置为可空,一对一同理) # models.ForeignKey('关联表', on_delete=models.SET_DEFAULT, default='默认值') on_delete=models.SET_DEFAULT, # 删除关联数据,与之关联的值设置为默认值(前提FK字段须要设置默认值,一对一同理) on_delete=models.SET, # 删除关联数据, a. 与之关联的值设置为指定值,设置:models.SET(值) b. 与之关联的值设置为可执行对象的返回值,设置:models.SET(可执行对象) '''
##DDL python magange.py makemigrations, migrate
-- auto-generated definition create table Three_grade ( id int auto_increment primary key, g_name varchar(32) not null ); create table Three_student ( id int auto_increment primary key, s_name varchar(16) not null, s_grade_id int not null, constraint Three_student_s_grade_id_ffbb8485_fk_Three_grade_id foreign key (s_grade_id) references hellodjango.Three_grade (id) );
##Three->>templates-->student_three_list.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Students List</title> </head> <body> <ul> {% for student in students %} <li>{{ student.s_name }}</li> {% endfor %} </ul> </body> </html>
##views.html
from django.http import HttpResponse from django.shortcuts import render # Create your views here. from django.template import loader from Three.models import Student, Grade def index(request): three_index = loader.get_template("three_index.html") context ={"student_name": '张三' } #有渲染,解析渲染引擎表达式的做用,若是不须要这些,直接open也能够 result = three_index.render(context=context) print(result) return HttpResponse(result) #多获取1 def get_grade(request): student = Student.objects.get(pk=1) grade= student.s_grade return HttpResponse("Grade %s",grade.g_name) #一获取多 def get_students(request): grade = Grade.objects.get(pk=1) students = grade.student_set.all() context = { "students":students } return render(request, "students_three_list.html", context=context)