如何将该SQL查询转换为Django ORM语句?

时间:2019-06-17 15:23:15

标签: mysql django django-models orm

我有3种型号:

awk '
BEGIN{
  key="1,1A,1B,2,3,4,4A,6,Z"
  value="1,2,3,4,5,6,7,8,9"
  split(key,array1,",")
  num=split(value,array2,",")
  for(i=1;i<=num;i++){
    pair[array1[i]]=array2[i]
  }
}
{
  for(i=1;i<=NF;i++){
    if($i in pair){
      $i=pair[$i]
    }
  }
}
1
'   Input_file

我想使用#Appointment class Appointment(models.Model): doctor = models.ForeignKey( Doctor, on_delete=models.CASCADE, related_name='doctor_appointment') patient = models.ForeignKey( Patient, on_delete=models.CASCADE, related_name='patient_appointment') scheduled = models.DateTimeField(auto_now_add=True) # Doctor class Doctor(models.Model): user_id = models.TextField(unique=True) first_name = models.CharField(max_length=100, blank=False) last_name = models.CharField(max_length=100, blank=False) # Patients class Patient(models.Model): user_id = models.TextField(unique=True) first_name = models.CharField(max_length=100, blank=False) last_name = models.CharField(max_length=100, blank=False) 执行以下查询:

Django ORM

我想出了这句话:

SELECT 
d.first_name,
d.last_name,
d.specialty,
d.address,
a.scheduled

FROM appointment as a

LEFT JOIN patient as p ON p.id=a.patient_id

LEFT JOIN doctor as d ON d.id = a.doctor_id

WHERE p.user_id  = '12345';

,但检查其原始查询(ret = Appointment.objects.filter(patient__user_id='12345').values_list('doctor__first_name', 'doctor__last_name', 'scheduled') )后,我可以看到它已转换为一组ret.query

是否可以获取我想要的查询?

1 个答案:

答案 0 :(得分:1)

您应该避免考虑SQL查询; ORM的要点是它是基于 object 的。

出于同样的原因,请避免使用values_list之类的东西,除非您真的知道自己需要一个列表。您应该询问约会对象及其相关的Doctor和Patient对象。

您真正需要做的只是过滤约会并使用select_related来查询相关模型。然后,Django将根据是否允许空值使用INNER JOIN或LEFT JOIN做正确的事情。

例如,

Appointment.objects.filter(patient__user_id='12345').select_related('patient', 'doctor')