데이터 분석 기술 블로그

DB에 대하여(13)_ManyToManyField (feat. Django) 본문

DB

DB에 대하여(13)_ManyToManyField (feat. Django)

데이터분석가 이채은 2024. 4. 30. 22:52

Django에서는 'ManyToManyField'로 중개모델을 자동으로 생성합니다.

1. Django ManyToManyField

환자 모델에 ManyToManyField를 작성합니다.

# hospitals/models.py

class Patient(models.Model):
    # ManyToManyField 작성
    doctors = models.ManyToManyField(Doctor)
    name = models.TextField()
    
    def __str__(self):
        return f'{self.pk}번 환자 {self.name}'

# Reservation Class 주석 처리

데이터베이스 초기화 후 Migration 진행 및 shell_plus 실행합니다.

생성된 중개 테이블 hosptals_patient_doctors를 확인합니다.


의사 1명과 환자 2명을 생성합니다.

doctor1 = Doctor.objects.create(nmae='allie')
patient1 = Patient.objects.create(nmae='carol')
patient2 = Patient.objects.create(nmae='duke')

예약을 생성합니다.(환자가 예약)

# patient1이 doctor1에게 예약
patient1.doctors.add(doctor1)

# patient1 - 자신이 예약한 의사목록 확인
patient1.doctors.all()
<QuerySet [<Doctor: 1번 의사 allie>]>

# doctor1 - 자신이 예약된 환자목록 확인
doctor1.patient_set.all()
<QuerySet [<Patient: 1번 환자 carol>]>

예약을 생성합니다.(의사가 예약)

# patient1이 patient2을 예약
doctor1.patient_set.add(patient2)

# doctor1 - 자신의 예약 환자목록 확인
doctor1.patient_set.all()
<QuerySet [<Patient: 1번 환자 carol>, <Patient: 2번 환자 duke>]>

# patient1, 2 - 자신이 예약한 의사목록 확인
patient1.doctors.all()
<QuerySet [<Doctor: 1번 의사 allie>]>

patient2.doctors.all()
<QuerySet [<Doctor: 1번 의사 allie>]>

중개 테이블에서 예약 현황을 확인합니다.


예약 취소하기 (삭제)

이전에는 Reservation을 찾아서 지워야 했지만 이제는. remove()로 삭제가 가능합니다.

# doctor1이 patient1 진료 예약 취소

doctor1.patient_set.remove(patient1)

doctor1.patient_set.all()
<QuerySet [<Patient: 2번 환자 duke>]>

patient1.doctors.all()
<QuerySet []>
# patient2가 doctor1 진료 예약 취소

patient2.doctors.remove(doctor1)

patient2.doctors.all()
<QuerySet []>

doctor1.patient_set.all()
<QuerySet []>