[英]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.