Django多个左联接

时间:2018-07-30 18:59:05

标签: django django-models

我想知道如何在Django中实现以下左连接sql查询。 我已经知道Person.objects.raw()

select person.name, phone.number, email.emailaddr, home.address
from person
left join phone
    on person.id = phone.person_id
left join email
    on person.id = email.person_id
left join home
    on person.id = home.person_id;

假定以下模型:

class Person(models.Model):
    name = models.CharField(max_length=30)

class Phone(models.Model):
    number = models.CharField(max_length=30)
    person = models.ForeignKey('Person')

class Email(models.Model):
    emailaddr = models.CharField(max_length=30)
    person = models.ForeignKey('Person')

class Home(models.Model):
    address = models.CharField(max_length=30)
    person = models.ForeignKey('Person')

1 个答案:

答案 0 :(得分:2)

我认为这应该可以解决问题:

Person.objects.values_list(
    'name', 
    'phone__number', 
    'email__emailaddr', 
    'home__address'
)