1

I have a SQL query which I am trying to make it as a Django ORM, tried many ways but didn't get the exact solution for it.

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 Model are,

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)
aakash singh
  • 267
  • 5
  • 19

1 Answers1

1

Need to use select_related

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

select_related works by creating a SQL join docs

frfahim
  • 515
  • 9
  • 21
  • Hi @Farhadur, this works fine can I also get the reverse of it meaning with the help of customer can I get all products for that customer? – aakash singh Oct 24 '18 at 08:58
  • Yes you can, you have to use `prefetch_related` [related article](https://medium.com/@lucasmagnum/djangotip-select-prefetch-related-e76b683aa457) – frfahim Oct 24 '18 at 12:06