我一直在努力弄清楚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 quetions / answers。此外,搜索谷歌。但我想我不知道我应该怎么做。
这是我想要实现的目标。
我想找到有特定手机号码的患者,然后我想找到他们预约的医生和诊所。
我在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及其查询系统的新手。
可以请某人建议如何操作以及改进模型的任何方法。
谢谢
答案 0 :(得分:1)
尝试这样的事情:
dpa_QS = DoctorPatientAppointment.objects.filter(patient__mobile=12345)
for dpa in dpa_QS:
print(dpa.doctor)
print(dpa.clinic)
可能需要进行优化,但它会起作用。