表单的建立
from django.db import models # Create your models here. #创建教室表单 class Class_list(models.Model): id=models.AutoField(primary_key=True) cname=models.CharField(max_length=32) first_day=models.DateField() def __str__(self): return self.cname #创建老师表单 class Teacher(models.Model): tname=models.CharField(max_length=32) cid=models.ManyToManyField("Class_list") #设置manytomant 外键,他自动生成了第三个关联老师和教室的对应关系表
第三张表上放的每一个值实际上 可以指带的是一个对象(一条数据) 而不单单是一个id# 也可以是id}
查看老师信息
html页面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>teacher_list</title> </head> <body> {% csrf_token %} <div class="c1"> <button type="button"><span><a href='{% url 'add_teacher' %}' >新增</a></span></button> </div> <div class="c2"> <table border="2"> <thead> <tr> <th>序号</th> <th>id</th> <th>姓名</th> <th>班级</th> <th>功能</th> </tr> </thead> <tbody> {% for teacher in teacher_list %} <tr> <td> {{ forloop.counter }}</td> <td>{{ teacher.id }}</td> <td>{{ teacher.tname }}</td> <td> {% for class in teacher.cid.all %} {{ class.cname }} {% endfor %} </td> <td> <a href="">aaa</a> {# <button type="button"><span><a href="{% url 'delete_class' class.id %}">删除</a></span></button>#} <button type="button"><span><a href="{% url 'edit_teacher' teacher.id %} ">编辑</a></span></button> </td> </tr> {% endfor %} </tbody> </table> </div> </body> </html>
编辑老师信息
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Title</title> </head> <body> <form action="{% url 'edit_teacher' teacher.id %}" method="post"> {% csrf_token %} <input type="text" name="id" style="display:none" value="{{ teacher.id }}"> <span>名字</span> <input type="text" name="tname" value="{{ teacher.tname }}"> <span>班级</span> <select name="class_id" id="" multiple> {% for class in class_list %} {# 注意这里写法,因为第三张表上放的每一个值实际上指的是一个对象(一条数据) 而不单单是一个id#} {# 所以这里这样写, #} {% if class in teacher.cid.all %} <option selected value="{{ class.id }}" >{{ class.cname }}</option> {% else %} <option value="{{ class.id }}" >{{ class.cname }}</option> {% endif %} {% endfor %} </select> <button type="submit">提交</button> </form> </body> </html>
viwe中的写法
查询
def teacher_list(request): ret=models.Teacher.objects.all() print(ret) return render(request,'teacher_list.html',{'teacher_list':ret})
编辑
#多对多之编辑 def edit_teacher(request,args): tid=args ret=models.Teacher.objects.get(id=tid) class_list=models.Class_list.objects.all() return render(request,'edit_teacher.html',{'teacher':ret,'class_list':class_list})