title: Django join tables with ORM and conditional Where clause
body: <p>I have 4 tables to join; Personnels,Machines and Locations. I want to join these tables and add where clause to end of the ORM query if request body includes filtering data. Here is my models and raw query (I want to write this query in django ORM) and sample if condition for where clause;</p>
  
  <p>Models ; </p>
  
  <pre><code>class Sales(models.Model):
      MachineId = models.ForeignKey(Machines,on_delete=models.CASCADE,db_column='MachineId',related_name='%(class)s_Machine')
      PersonnelId = models.ForeignKey(Personnels,on_delete=models.CASCADE,db_column='PersonnelId',related_name='%(class)s_Personnel')
      LocationId = models.ForeignKey(Locations,on_delete=models.CASCADE,db_column='LocationId',related_name='%(class)s_Location')
      class Meta:
          db_table = "Sales"
  
  class Machines(models.Model):
      Name = models.CharField(max_length=200)
      Fee = models.DecimalField(max_digits=10,decimal_places=3)
      class Meta:
          db_table = "Machines"
  
  class Personnels(models.Model):
      name = models.CharField(max_length=200)
      surname = models.CharField(max_length=200)
      class Meta:
          db_table = "Personnels"
  
  
  class Locations(models.Model):
      Latitude = models.FloatField()
      Longitude = models.FloatField()
      LocationName = models.CharField(max_length=1000)
      class Meta:
          db_table = "Locations"
  </code></pre>
  
  <p>As you see I have 4 models. "Sales" table has foreignkeys to others. I want to get all informations in tables with using these foreign keys.(With Inner Join)</p>
  
  <pre><code>    query = '''select * from "Sales" as "SL" INNER JOIN "Personnels" as "PL" ON ("SL"."PersonnelId" = "PL"."user_id") INNER JOIN "Machines" as "MC" ON ("SL"."MachineId" = "MC"."id")    INNER JOIN "Locations" as "LC" ON ("SL"."LocationId" = "LC"."id") '''
      if request.method=='POST':
          if request.data['personnel_name'] and request.data['personnel_name'] is not None:
              personnel_name = request.data['personnel_name']
              condition = '''WHERE "PL"."name" = '{0}' '''.format(personnel_name)
              query = query+condition
  </code></pre>
  
  <p>As it is seen, there are lots of quotes (if I don't write,postgresql makes some trouble) and code is not clean. </p>
  
  <p>My question is, how can I write this query with using django ORM? As you see, I want to add where conditions dynamically. How can I achieve that? </p>