rahnama7m
rahnama7m

Reputation: 977

Queryset for models FK relations in django

These are my models and fields:

Models.py

Brif of my system:

  1. As seen from my model file, in this system, the courses have a pre-requisite state.Untile preson can't pass pre-requisite of course, can't take the course.
  2. Each course is presented for enrollment in model named: 'Curriculum'.

And finally my problem is:

In fact, I know that I must first check student enrollment and find the 'Curriculum' that he have,and by this, find all course of student. Then,among the course I will find the course that have prerequisite_of_course and finally check for student for each of this prerequisite course check that student enroll in course curriculum!

It's very hard for me to write this query? Can you help me?

Upvotes: 1

Views: 145

Answers (1)

Sanjay Kumar
Sanjay Kumar

Reputation: 139

Check this, this can help your query

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

Upvotes: 1

Related Questions