Django查询:使用两个字段连接两个模型

时间:2014-06-08 16:18:56

标签: python django django-queryset

我有以下型号:

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

学术记录包含每个都有语言代码的主题列表,主题时间包含主题和语言代码。

使用给定的AcademicRecord,如何才能获得与AcademicRecordSubjects所拥有的AcademicRecord匹配的主题时间?

这是我的方法,但它会产生比所需更多的查询:

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

我想使用django ORM而不是原始SQL

进行查询

SubjectTime语言组必须与Subject的语言组匹配

2 个答案:

答案 0 :(得分:3)

鉴于AcademicRecord实例academic_record,它是

SubjectTime.objects.filter(subject__academicrecordsubject_set__academic_record=academic_record)

SubjectTime.objects.filter(subject__academicrecordsubject__academic_record=academic_record)

结果反映了这些ORM查询在SQL中成为联接的所有行。为避免重复,请使用distinct()

现在这将更容易,如果我有一个django shell来测试:)

答案 1 :(得分:3)

我得到了它,部分归功于@RobertJørgensgaardEng

我的问题是如何使用多个1字段进行内部连接,其中F对象随意出现。
正确的查询是:

SubjectTime.objects.filter(subject__academicrecordsubject__academic_record=record,
                           subject__academicrecordsubject__language_group=F('language_group'))