I have three tables,result, course and study, they are like follows
class Study(models.Model):
id_study = models.IntegerField(primary_key=True)
study_name = models.CharField(max_length=45)
description = models.CharField(max_length=45, blank=True, null=True)
language = models.CharField(max_length=45)
number_of_years = models.CharField(max_length=45)
class Course(models.Model):
id_course = models.AutoField(primary_key=True)
course_name = models.CharField(max_length=45, blank=True, null=True)
description = models.CharField(max_length=45, blank=True, null=True)
credits = models.CharField(max_length=45, blank=True, null=True)
teacher_id_teacher = models.ForeignKey('Teacher', models.DO_NOTHING, db_column='teacher_id_teacher')
study_id_study = models.ForeignKey('Study', models.DO_NOTHING, db_column='study_id_study')
class Exam(models.Model):
id_exam = models.AutoField(primary_key=True)
room = models.CharField(max_length=45, blank=True, null=True)
resit = models.CharField(max_length=45, blank=True, null=True)
date = models.DateField(blank=True, null=True)
time = models.TimeField(blank=True, null=True)
course_id_course = models.ForeignKey(Course, models.DO_NOTHING, db_column='course_id_course')
class Result(models.Model):
id_result = models.AutoField(primary_key=True)
grade = models.IntegerField(blank=True, null=True)
exam_id_exam = models.ForeignKey(Exam, models.DO_NOTHING, db_column='exam_id_exam')
date = models.DateField(blank=True, null=True)
student_id_student = models.ForeignKey('Student', models.DO_NOTHING, db_column='student_id_student')
passed = models.CharField(max_length=45, blank=True, null=True)
I want to get a result object depending on the study_id I give
Result depends on Exam, Exam depends on Course and Course depends on study
Thanks in advance
You can follow relationships in queries by using the double underscore notation
Result.objects.filter(
exam_id_exam__course_id_course__study_id_study__id=study_id
)
For what it's worth: you have an odd naming convention for your foreign keys, usually a foreign key to a model named Exam
would be named exam
, you are already setting db_column
for each foreign key so you don't need to name them this way. If you changed their names to be the model name lowercase it would look like this which is probably more readable
Result.objects.filter(exam__course__study__id=study_id)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.