title: Django query: Joining two models with two fields
body: <p>I have the following models:</p>
  
  <pre><code>class AcademicRecord(models.Model):
      record_id = models.PositiveIntegerField(unique=True, primary_key=True)
      subjects = models.ManyToManyField(Subject,through='AcademicRecordSubject')
      ...
  
  
  class AcademicRecordSubject(models.Model):
      academic_record = models.ForeignKey('AcademicRecord')
      subject = models.ForeignKey('Subject')
      language_group = IntegerCharField(max_length=2)
      ...
  
  
  class SubjectTime(models.Model):
      time_id = models.CharField(max_length=128, unique=True, primary_key=True)
      subject = models.ForeignKey(Subject)
      language_group = IntegerCharField(max_length=2)
      ...
  
  
  class Subject(models.Model):
      subject_id = models.PositiveIntegerField(unique=True,primary_key=True)
      ...
  </code></pre>
  
  <p>The academic records have list of subjects each with a language code and the subject times have a subject and language code.</p>
  
  <p>With a given <code>AcademicRecord</code>, how can I get the subject times that matches with the <code>AcademicRecordSubjects</code> that the <code>AcademicRecord</code> has?</p>
  
  <p>This is my approach, but it makes more queries than needed:</p>
  
  <pre><code># record is the given AcademicRecord
  times = []
  for record_subject in record.academicrecordsubject_set.all():
      matched_times = SubjectTime.objects.filter(subject=record_subject.subject)
      current_times = matched_times.filter(language_group=record_subject.language_group)
      times.append(current_times)
  </code></pre>
  
  <p>I want to make the query using django ORM not with raw SQL</p>
  
  <p><code>SubjectTime</code> language group has to match with <code>Subject</code>'s language group aswell</p>