简体   繁体   中英

How can I convert this SQL query to a Django ORM statement?

I have 3 models:

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

And I want to execute the below query using 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';

I've come up with this statement:

ret = Appointment.objects.filter(patient__user_id='12345').values_list('doctor__first_name', 'doctor__last_name', 'scheduled')

but upon examining its raw query ( ret.query ) I can see that this is translated to a set of INNER JOINS .

Is there a way to get the query I want?

You should avoid thinking in terms of SQL queries; the point of the ORM is that it is object based.

For the same reason, avoid things like values_list unless you really know you need a list. You should be asking for Appointment objects and their related Doctor and Patient objects.

What you really need to do is just to filter on Appointments and use select_related to query the related models. Django will then do the right thing, using INNER JOIN or LEFT JOIN depending on whether null values are permitted.

So, for example:

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

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