DjangoORM一對多&多對多操作


簡要說明

通過操作對象的方式操作數據庫

詳細步驟

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

 
 
 
         
  1. teacher = Teacher.objects.get(id = 1)
  2. student = teacher.student_set.get(id = 1)
  3. student.delete()

刪除和該teacher相關的所有student

 
 
 
         
  1. teacher = Teacher.objects.get(id = 1)
  2. student = teacher.student_set.get(id = 1)
  3. student.teacher.delete()

數據庫多對多操作:

 
 
 
         
  1. group = Group.objects.get(id = 1)
  2. studentList = group.members.all()
  3. groupList = student.group_set.all()
  4. MemberShip(group = newGroup, student=newStudent).save()





免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM