Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inner join 4 tables in Django?

We want to retrieve all table records at a time how to implement like SQL queries in django orm.

Example SQL query:

select * 
from Company_info 
inner join Bank_info on Bank_info.manufacturer = Company_info.manufacturer
inner join Company_info on Company_info.manufacturer = Company_info.manufacturer
inner join Transport_info on Transport_info.manufacturer = Company_info.manufacturer

Code:

class Manufacturer(models.Model):
    name = models.CharField(max_length=42)

class Bank_info(models.Model):
    account = models.CharField(max_length=42)
    manufacturer = models.ForeignKey(Manufacturer, on_delete= models.CASCADE)

class Company_info(models.Model):
    name= models.CharField(max_length=42)
    manufacturer = models.ForeignKey(Manufacturer, on_delete= models.CASCADE)

class Transport_info(models.Model):
    name= models.CharField(max_length=42)
    manufacturer = models.ForeignKey(Manufacturer, on_delete= models.CASCADE)
like image 885
Manjuanth V M Avatar asked Oct 27 '25 05:10

Manjuanth V M


1 Answers

You can use prefetch_related for this, as mentioned in comments:

Manufacturer.objects.all().prefetch_related('related_name2', 'related_name3', 'related_name4')

This, in fact, will not perform an SQL INNER JOIN, but will join prefetched objects on Python level - this will decrease hits to DB when using related object fields.

like image 156
Charnel Avatar answered Oct 28 '25 17:10

Charnel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!