Django 다대다 첨삭 고사

2694 단어
다대다관계
  • 다대다
  • 정의 다중 ManyToManyField 필드
    from django.db import models
    
    #    
    class Student(models.Model):
        name = models.CharField(max_length=32)
    
    
    #    
    class Teacher(models.Model):
        name = models.CharField(max_length=32)
        students = models.ManyToManyField(to='Student',related_name='stu')
  • 멀티태스킹
  • 레코드 추가
  • #       
    teacherobj = models.Teacher.objects.filter(id=1).first()
    studentobj = models.Student.objects.filter(id=1).first()
    teacherobj.students.add(studentobj)
    return Response('ok')
    #       
    studentobj = models.Student.objects.filter(id=1).first()
    teacherobj = models.Teacher.objects.filter(id=2).first()
    studentobj.stu.add(teacherobj)
    return Response('ok')
  • 다중 레코드 추가
  • #         
    teacherobj = models.Teacher.objects.filter(id=3).first()
    teacherobj.students.add(*[1,2,3,4])
    teacherobj.save()
    #         
    studentobj = models.Student.objects.filter(id=2).first()
    studentobj.stu.add(*[3,4])
    studentobj.save()
  • 중복되지 않는 레코드 추가
  • #         
    teacherobj = models.Teacher.objects.filter(id=3).first()
    teacherobj.students.set(*[1,2,3,4])
    teacherobj.save()
    #         
    studentobj = models.Student.objects.filter(id=2).first()
    studentobj.stu.set(*[3,4])
    studentobj.save()
  • 멀티 쿼리
    #           
    teacherobj = models.Teacher.objects.filter(id=3).first()
    stuobj = teacherobj.students.all()
    #          
    studentobj = models.Student.objects.filter(id=2).first()
    teacherobj = studentobj.stu.all()
  • 멀티 쌍 업데이트
    #        
    teacherobj = models.Teacher.objects.filter(id=3).first()
    teacherobj.students.set([1,2,3,4])
    #        
    studentobj = models.Student.objects.filter(id=3).first()
    studentobj.stu.set([1,2,3,4])
  • 멀티 페어 삭제
    #         
    teacherobj = models.Teacher.objects.filter(id=3).first()
    studentobj = models.Student.objects.filter(id=2).first()
    teacherobj.students.remove(studentobj)
    #         
    studentobj = models.Student.objects.filter(id=3).first()
    teacherobj = models.Teacher.objects.filter(id=4).first()
    studentobj.stu.remove(teacherobj)
    studentobj.save()
    #         
    teacherobj = models.Teacher.objects.filter(id=1).first()
    teacherobj.students.clear()
    teacherobj.save()
    #         
    studentobj = models.Student.objects.filter(id=3).first()
    studentobj.stu.clear()
    studentobj.save()
  • python 기반 3.6 Django 2.1.4
  • 좋은 웹페이지 즐겨찾기