简要说明
通过操作对象的方式操作数据库
详细步骤
通过操作对象的方式操作数据库
models.py的结构是:
如果models.py中外键定义没有写 related_name=’student_teacher’, 可以直接用
studentList = teacher.student_teacher.all() 可以改写成:
teacher = Teacher.objects.get(id = 1)
studentList = teacher.student_set.all()
============================================================================================
from myblog.models import Student,Teacher
def student_list(request):
t = loader.get_template("student_list.html")
#studentList = Student.objects.all()
teacher = Teacher.objects.get(id = 1)
studentList = teacher.student_teacher.all()
c = Context({"studentList":studentList})
return HttpResponse(t.render(c))
数据库一对多的操作:
查找:
方法一:
通过Student表来查:
查找Student表中,teacher_id为1的老师名称
studentList = Student.objects.all()
模板中使用:
student.teacher.name来获取外键的name属性值
方法二:
通过Teacher表来查:
teacher = Teacher.objects.get(id = 1) #先查到id 为1 的teacher
studentList = teacher.student_teacher.all() #通过外键查到studentlist
新增
方法一:
通过teacher得到student_set来创建
teacher.student_set.create(name = "tom",...)
方法二:
创造一个student对象,添加到teacher的student_set属性中
student = Student(name = "tom",....)
teacher.student_set.add(student)
修改
只删除student
teacher = Teacher.objects.get(id = 1)
student = teacher.student_set.get(id = 1)
student.delete()
删除和该teacher相关的所有student
teacher = Teacher.objects.get(id = 1)
student = teacher.student_set.get(id = 1)
student.teacher.delete()
数据库多对多操作:
group = Group.objects.get(id = 1)
studentList = group.members.all()
groupList = student.group_set.all()
MemberShip(group = newGroup, student=newStudent).save()