使用ORM进行数据交互
前期准备
必备知识:ORM操作,数据库多表操作、Django部分知识。
三张表:班级、老师、学生
一对多关系:班级与学生
多对多关系:班级与老师
#创建班级表 class Classes(models.Model): title = models.CharField(max_length=32) n=models.ManyToManyField('Teachers') #创建老师表 class Teachers(models.Model): name= models.CharField(max_length=32) age=models.IntegerField(default=30) gender=models.BooleanField(default=False) is_married=models.BooleanField(default=True) address = models.CharField(max_length=50,default='xiaogan') #创建学生表 class Student(models.Model): username=models.CharField(max_length=32) age=models.IntegerField() #只能写true和false gender=models.BooleanField() cs=models.ForeignKey(Classes,on_delete=models.DO_NOTHING) address=models.CharField(max_length=50,default='xiaogan')
目标
1.对学生,班级的增删改查 2.为班级分配老师
URL路由
from django.contrib import admin from django.urls import path from app01.views import * urlpatterns = [ path('admin/', admin.site.urls), path('classes.html/',get_classes), path('addclasses.html/',add_classes), path('delclasses.html/',del_classes), path('altclasses.html/',alt_classes), path('student.html/', get_student), path('addstudent.html/',add_student), path('delstudent.html/',del_student), path('altstudent.html/', alt_student), path('choose_teacher.html/', choose_teacher), path("ajax_get_date.html/", ajax_get_data), ]
创建表
from django.db import models # 一对多:班级与学生 # 多对多:班级与老师 # Create your models here. #创建班级表 class Classes(models.Model): title = models.CharField(max_length=32) n=models.ManyToManyField('Teachers') #创建老师表 class Teachers(models.Model): name= models.CharField(max_length=32) age=models.IntegerField(default=30) gender=models.BooleanField(default=False) is_married=models.BooleanField(default=True) address = models.CharField(max_length=50,default='xiaogan') #创建学生表 class Student(models.Model): username=models.CharField(max_length=32) age=models.IntegerField() #只能写true和false gender=models.BooleanField() cs=models.ForeignKey(Classes,on_delete=models.DO_NOTHING) address=models.CharField(max_length=50,default='xiaogan')
视图函数
from django.shortcuts import render,HttpResponse,redirect from app01 import models # Create your views here. def get_classes(request): cls_list=models.Classes.objects.all() print(cls_list) # return HttpResponse('ok') return render(request,"get_classes.html",{'cls_list':cls_list}) def add_classes(request): if request.method=='GET': return render(request,'add_classes.html') elif request.method=="POST": title=request.POST.get('title') print(title) # ret=models.Classes.objects.all().values('title') # for Title in ret: # if Title['title']==title: # print(Title) models.Classes.objects.create(title=title) #注意这里是url路径 return redirect('/classes.html') def del_classes(request): nid=request.GET.get('nid') print(nid) ret=models.Classes.objects.filter(id=nid).delete() print(ret) return redirect('/classes.html/') def alt_classes(request): if request.method=="GET": nid = request.GET.get('nid') obj=models.Classes.objects.filter(id=nid)[0] return render(request,'alt_classes.html',{'obj':obj}) elif request.method=="POST": nid=request.GET.get("nid") title=request.POST.get("title") models.Classes.objects.filter(id=nid).update(title=title) return redirect("/classes.html/") def get_student(request): stu_list = models.Student.objects.all() print(stu_list) # return HttpResponse('ok') return render(request, "get_student.html", {'stu_list': stu_list}) def add_student(request): if request.method=='GET': cs_list=models.Classes.objects.all() print(cs_list) return render(request,'add_student.html',{'cs_list':cs_list}) elif request.method=="POST": name=request.POST.get('name') age=request.POST.get('age') gender=request.POST.get('gender') cs_id=request.POST.get('class') address=request.POST.get('address') print(name,age,gender,cs_id,address) # ret=models.Classes.objects.all().values('title') # for Title in ret: # if Title['title']==title: # print(Title) models.Student.objects.create(username=name,age=age,gender=gender,cs_id=cs_id,address=address) #注意这里是url路径 return redirect('/student.html') def del_student(request): nid = request.GET.get('nid') print(nid) ret = models.Student.objects.filter(id=nid).delete() print(ret) return redirect('/student.html/') def alt_student(request): if request.method=="GET": nid = request.GET.get('nid') obj=models.Student.objects.filter(id=nid)[0] cs_list = models.Classes.objects.all() return render(request,'alt_student.html',locals()) elif request.method=="POST": nid=request.GET.get("nid") name = request.POST.get('name') age = request.POST.get('age') gender = request.POST.get('gender') cs_id = request.POST.get('class') address = request.POST.get('address') print(name, age, gender, cs_id, address) models.Student.objects.filter(id=nid).update(username=name,age=age,gender=gender,cs_id=cs_id,address=address) return redirect("/student.html/") def choose_teacher(request): if request.method=="GET": nid=request.GET.get('nid') print(nid) #多对多的字段创建的Class表,我们可以通过id,拿到这个班级对象 # cls=models.Classes.objects.filter(id=nid).first() #当前班级的老师列表 cls_teacher=cls.n.all() #所有老师的列表 teacher_list=models.Teachers.objects.all() teachers=[] #如果teacher在cls_list中,说明,这个老师已经是这个班级的任课老师 for teacher in teacher_list: if teacher in cls_teacher:continue else:teachers.append(teacher) return render(request,"set_teacher.html",{'teachers':teachers,'cls_teacher':cls_teacher,'nid':nid}) elif request.method=="POST": #获取现在操作的班级id nid=request.GET.get("nid") #获取现在所选老师 id teacher_id=request.POST.get('teacher_id') print(nid,teacher_id) Class=models.Classes.objects.filter(id=nid).first() Class.n.add(2) # return render(request, "get_classes", {'nid': nid}) return redirect("/classes.html/")
HTML代码
班级首页
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div> <table border="1"> <thead> <tr> <th>ID</th> <th>名称</th> <th>操作</th> </tr> </thead> <tbody> {% for row in cls_list %} <tr> <td> {{ row.id }} </td> <td> {{ row.title }} </td> <td> <a href="/delclasses.html?nid={{ row.id }}">删除</a> <a href="/altclasses.html?nid={{ row.id }}">编辑</a> <a href="/choose_teacher.html?nid={{ row.id }}">分配老师</a> </td> </tr> {% endfor %} <tr> <td> </td> <td> <a href="/addclasses.html/">添加</a> </td> </tr> </tbody> </table> </div> </body> </html>
编辑班级名称代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/altclasses.html/?nid={{ obj.id }}" method="post"> {% csrf_token %} <p><input type="text" name="title" value="{{ obj.title }}"></p> <!--<p><input type="text" name="id" value="{{ obj.id }}"></p>--> <input type="submit"> </form> </body> </html>
添加班级代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/addclasses.html/" method="post"> {% csrf_token %} <p>班级:<input type="text" name="title"></p> <p><input type="submit"></p> </form> </body> </html>
为班级分配任课老师
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <p>班级现在的任课老师: {% for teacher in cls_teacher %} <p>{{ teacher.name }}</p> {% endfor %} </p> 添加新的任课老师:<br> <form action="/choose_teacher.html/?nid={{ nid }}" method="post"> {% csrf_token %} <select multiple size=10 name="teacher_id"> {% for item in teachers %} <option value="{{ item.id }}">{{ item.id }} {{ item.name }}</option> {% endfor %} </select> <!-- {{ item.name }}--> <br> <input type="submit"> </form> </body> </html>
学生首页
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div> <table border="1"> <thead> <tr> <th>ID</th> <th>姓名</th> <th>年龄</th> <th>性别</th> <th>班级</th> <th>住址</th> <th>行为</th> </tr> </thead> <tbody> {% for row in stu_list %} <tr> <td> {{ row.id }} </td> <td> {{ row.username }} </td> <td> {{ row.age }} </td> <td> {{ row.gender }} </td> <td> {{ row.cs.title }} </td> <td> {{ row.address }} </td> <td> <a href="/delstudent.html?nid={{ row.id }}">删除</a> <a href="/altstudent.html?nid={{ row.id }}">编辑</a> </td> </tr> {% endfor %} <tr> <td> </td> <td> <a href="/addstudent.html/">添加</a> </td> </tr> </tbody> </table> </div> </body> </html>
添加学生代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/addstudent.html/" method="post"> {% csrf_token %} <p>学生姓名:<input type="text" name="name"></p> <p>学生年龄:<input type="text" name="age"></p> <p>性别:男<input type="radio" name="gender" value='1'> 女<input type="radio" name="gender" value='0' > </p> <select name="class"> {% for row in cs_list %} {{ row.id }} 班级:<option value="{{ row.id }}">{{ row.title }}</option> {% endfor %} </select> <p>住址:<input type="text" name="address"></p> <p><input type="submit"></p> </form> </body> </html>
编辑学生代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/altstudent.html/?nid={{ obj.id }}" method="post"> {% csrf_token %} <p>学生姓名:<input type="text" name="name"></p> <p>学生年龄:<input type="text" name="age"></p> <p>性别:男<input type="radio" name="gender" value='1'> 女<input type="radio" name="gender" value='0' > </p> <select name="class"> {% for row in cs_list %} {{ row.id }} 班级:<option value="{{ row.id }}">{{ row.title }}</option> {% endfor %} </select> <p>住址:<input type="text" name="address"></p> <p><input type="submit"></p> <input type="submit"> </form> </body> </html>
注意:删除对应相应的视图函数处理
分析与总结
ORM:
具体看前几篇文章。
视图函数:
1.每次的请求可能有get数据,也有post发送过来的数据,如果处理方式不同,做相应的处理。
2.redirect(url):跳转到哪个页面下,这里面的url对应url里面的路径。
HTML:
1.
通过form表单向服务端发送数据。
客户端发送的是键值对,服务端接收到的也是键值对。
所以表单标签一定要使用name指定键名,text,password的值为用户输入,radio,select的值为用户选择,所以一定要设置对应每个选项的value值。
注意:比如男,女这种选项,value设置为"1","0",服务端存储到数据中会进行处理,转换为True,Flase。
2.通过id对应数据库表里的记录,而这个id通过get方式发送给服务端。