데이터 분석 기술 블로그

DB에 대하여(14)_'through' argument (feat. Django) 본문

DB

DB에 대하여(14)_'through' argument (feat. Django)

데이터분석가 이채은 2024. 5. 1. 01:27

'through' argument

중개 테이블에 '추가 데이터'를 사용해 M:N 관계를 형성하려는 경우에 사용합니다.


through 설정 및 Reservation Class를 수정합니다. 

이제는 예약 정보에 "증상"과 "예약일"이라는 추가 데이터가 생깁니다.

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

class Reservation(models.Model):
    doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE)
    patient = models.Foreignkey(Patient, on_delete=models.CASCADE)
    symptom = models.TextField()
    reserved_at = models.DateTimeField(auto_now_add=True)
    
    def __str__(self):
        return f'{self.doctor.pk}번 의사의 {self.patient.pk}번 환자'

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

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

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

예약 생성 방법 (1) _ Reservation class를 통한 예약 생성

reservation1 = Reservation(doctor=doctor1, patient=patient1, symptom='headache')
reservation1.save()

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

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

예약 생성 방법 (2) _ Patient 객체를 통한 예약 생성(through_defaults)

patient2.doctors.add(doctor1, through_defaults={'symptom': 'flu'})

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

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

생성된 예약을 확인합니다.


의사와 환자가 각각 예약을 삭제합니다.

doctor1.patient_set.remove(patient1)

patient2.doctors.remove(doctor1)

M:N 관계 주요 사항