用于多个左联接的SQL查询的Django ORM

时间:2018-10-24 06:00:18

标签: python sql django orm django-queryset

我有一个SQL查询,试图将其作为Django ORM,尝试了多种方法,但未获得确切的解决方案。

select c.* from product p 
left join voucher v on v.id = p.voucher_id
left join customer c on c.id = v.customer_id
where p.id=3;

Django模型是

class Customer(models.Model):
    customer_name = models.CharField(max_length=200, default="", db_index=True)
   mobile = models.IntegerField(default='')

class Voucher(models.Model):
    voucher_name = models.CharField(max_length=100, default='')
    customer = models.ForeignKey(Customer,db_index=True)

class Product(models.Model):
    product_name = models.CharField(max_length=100, default='')
    rate = models.FloatField(max_length=50)
    voucher = models.ForeignKey(Voucher, db_index=True)

1 个答案:

答案 0 :(得分:1)

需要使用select_related

ORM:Product.objects.filter(id=3).select_related('voucher__customer')

select_related通过创建SQL连接docs

来工作