简体   繁体   中英

Django: confused by manytomany relationship

I have been trying figure out the working of pre_fetch and manytomany relationship. It is confusing for me. I don't get it.

I have these models:

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') 

I went through the documentation and many SO quetions/answers. Also, searched Google. But I think I am not getting it how should I do this.

Here is what I want to achieve.

I want to find Patients that have a given mobile number and then I want to get which doctors and clinics they have appointments with.

I tried many solutions found on SO. It is not working.

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 = .....

I feel this is not right. I tried few other ways as well. I don't even remember what I have tried all day from the internet. All I know is nothing works and now I am lost.

In SQL it is simple with JOINs but I am new to Django and its query system.

Can please someone suggest how to do it and any ways to improve my models.

Thank you

Try something like this:

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

It may need to be optimized, but it will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM