Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django query: Joining two models with two fields

I have the following models:

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)
    ...

The academic records have list of subjects each with a language code and the subject times have a subject and language code.

With a given AcademicRecord, how can I get the subject times that matches with the AcademicRecordSubjects that the AcademicRecord has?

This is my approach, but it makes more queries than needed:

# 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)

I want to make the query using django ORM not with raw SQL

SubjectTime language group has to match with Subject's language group aswell

like image 742
Alejandro Garcia Avatar asked Mar 21 '26 09:03

Alejandro Garcia


1 Answers

I got it, in part thanks to @Robert Jørgensgaard Eng

My problem was how to do the inner join using more than 1 field, in which the F object came on handly.
The correct query is:

SubjectTime.objects.filter(subject__academicrecordsubject__academic_record=record,
                           subject__academicrecordsubject__language_group=F('language_group'))
like image 111
Alejandro Garcia Avatar answered Mar 23 '26 01:03

Alejandro Garcia



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!