简体   繁体   English

Django:被许多关系所迷惑

[英]Django: confused by manytomany relationship

I have been trying figure out the working of pre_fetch and manytomany relationship. 我一直在尝试弄清pre_fetch和manytomany关系的工作方式。 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. 我仔细阅读了文档和许多SO问题/答案。 Also, searched Google. 此外,还搜索了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. 我尝试了许多在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. 在SQL中,使用JOIN很简单,但是我是Django及其查询系统的新手。

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. 可能需要对其进行优化,但是它将起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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