gpt4 book ai didi

python - Django 查询 : Joining two models with two fields

转载 作者:行者123 更新时间:2023-11-28 21:19:46 26 4
gpt4 key购买 nike

我有以下模型:

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,我如何才能获得与 AcademicRecord 具有的 AcademicRecordSubjects 相匹配的科目时间?

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

# 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 的语言组匹配

最佳答案

我明白了,部分要感谢@Robert Jørgensgaard Eng

我的问题是如何使用超过 1 个字段进行内部联接,其中 F 对象派上了用场。
正确的查询是:

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

关于python - Django 查询 : Joining two models with two fields,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24108167/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com