簡體   English   中英

Django:被許多關系所迷惑

[英]Django: confused by manytomany relationship

我一直在嘗試弄清pre_fetch和manytomany關系的工作方式。 這讓我感到困惑。 我不明白

我有以下模型:

class Clinic(models.Model):
     name = models.CharField(max_length=100)
     address = models.CharField(max_length=200)


class Doctor(models.Model):
     name = models.CharField(max_length=100)
     clinics = models.ManyToManyField(Clinic, through='ClinicDoctor', related_name='doctors')
     patients = models.ManyToManyField('Patient', through='DoctorPatientAppointment', related_name='doctors_appointment')

class ClinicDoctor(models.Model):
     doctor = models.ForeignKey(Doctor, related_name='doctorsF')
     clinic = models.ForeignKey(Clinic, related_name='clinicsF')


class Patient(models.Model):
     name = models.CharField(max_length=100)
     mobile = models.CharField(max_length=20)

class DoctorPatientAppointment(models.Model):
     patient = models.ForeignKey(Patient, related_name='patient_appointments')
     doctor = models.ForeignKey(Doctor, related_name='doctor_appointments') 
     clinic = models.ForeignKey(Clinic, related_name='clinic_appointments') 

我仔細閱讀了文檔和許多SO問題/答案。 此外,還搜索了Google。 但是我認為我不應該怎么做。

這是我想要實現的。

我想找到具有給定手機號碼的患者,然后我想獲得他們與之約會的醫生和診所。

我嘗試了許多在SO上找到的解決方案。 它不起作用。

Doc = Doctor.objects.all().prefetch_related('patients','clinics')

for doc in Doc:
   docString = .....
   for pat in doc.patients.filter(mobile=12345):
       patientString = .....
       for cli in doc.clinics.all():
            clinicString = .....

我覺得這是不對的。 我也嘗試了其他幾種方法。 我什至不記得我整天從互聯網上嘗試過的內容。 我所知道的一切都沒有,現在我迷路了。

在SQL中,使用JOIN很簡單,但是我是Django及其查詢系統的新手。

能否請別人提出建議以及如何改進我的模型。

謝謝

嘗試這樣的事情:

dpa_QS = DoctorPatientAppointment.objects.filter(patient__mobile=12345)
for dpa in dpa_QS:
    print(dpa.doctor)
    print(dpa.clinic)

可能需要對其進行優化,但是它將起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM