Django中模型FK关系的查询集

时间:2019-05-24 12:11:51

标签: python django django-models django-queryset

这些是我的模型和字段:

Models.py

  • 课程:
    • 标题
    • sl
  • 课程先决条件
    • this_course = ForeignKey(Course)
    • prerequisite_of_course = ForeignKey(课程)
  • 课程:
    • course = ForeignKey(课程)
    • 标题
    • sl
  • 报名:
    • 学生= ForeignKey(用户)
    • 课程= ForeignKey(课程)
    • 日期

我的系统精简版:

  
      
  1. 从我的模型文件中可以看到,在此系统中,课程有一个   先决条件状态。UntilePreson无法通过课程的先决条件,不能参加课程。
  2.   
  3. 每门课程均以以下模型提供:   “课程”。
  4.   

最后我的问题是:

实际上,我知道我必须首先检查学生的入学情况,并找到他拥有的“课程”,然后才能找到学生的所有课程。然后,在这门课程中,我将找到具有prerequisite_of_course的课程,并最终为每门前提课程的学生进行检查,并检查学生是否注册了课程!

我很难编写此查询吗?你能帮我吗?

1 个答案:

答案 0 :(得分:2)

选中此项,可以帮助您查询

# all student enrollments
all_enrollment = Enrollement.objects.filter(student=user)


# all students  curriculum_ids
all_curriculum_ids =  all_enrollment.values_list('curriculum', flat=True)

# all curriculum object list
all_curriculum = Curriculum.objects.filter(pk__in=all_curriculum_ids)


#  all student curriculum courses
all_courses_ids = all_curriculum.values_list('course', flat=True)

# we have all courses that student participated
all_courses = Course.objects.filter(pk__in=all_courses_ids)


# Now getting prerequisite_of_course ids
all_prerequisite_of_course_ids = CoursePrerequisite.objects.filter(this_course=this_course,prerequisite_course__isnull=False).value_list('prerequisite_course')


# here checking if student took all prequisite courses
for prerequisite_of_course_id in all_prerequisite_of_course_ids:
    if all_courses.filter((pk__in=prerequisite_of_course_id).exists():
        print("Paticipated")
    else:
        print("In this course id student did not participated", prerequisite_of_course_id)
        print("Tell Student to go and complete this course")