Tags
- 쟝고
- M:N
- Article & User
- drf
- count
- outer join
- update
- DB
- 뷰
- create
- Queue
- 통계학
- 백트래킹
- N:1
- Vue
- 스택
- stack
- SQL
- regexp
- migrations
- Tree
- 큐
- ORM
- 완전검색
- 트리
- Django
- 이진트리
- delete
- 그리디
- distinct
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Notice
Recent Posts
Link
데이터 분석 기술 블로그
DB에 대하여(13)_ManyToManyField (feat. Django) 본문
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 []>
'DB' 카테고리의 다른 글
DB에 대하여(15)_Django ManyToManyField (feat. Django) (0) | 2024.05.02 |
---|---|
DB에 대하여(14)_'through' argument (feat. Django) (0) | 2024.05.01 |
DB에 대하여(12)_중개 모델 (feat. Django) (0) | 2024.04.29 |
DB에 대하여(11)_Many to many relationships (feat. Django) (0) | 2024.04.28 |
DB에 대하여(10)_댓글 DELETE (feat. Django) (0) | 2024.04.27 |