簡要說明
通過操作對象的方式操作數據庫
詳細步驟
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()

