I'm trying to get all the Students which are enrolled to a list of specific courses (Say Course 1 and Course 2).
class Student(models.Model):
name = models.CharField(max_length=50, verbose_name="Student name")
courses = models.ManyToManyField(Course, related_name="students", blank=True)
def __str__(self):
return self.name
class Course(models.Model):
name = models.CharField(max_length=100, verbose_name="Course Name")
def __str__(self):
return self.name
If I do:
result = Student.objects.filter(courses__in=[1,2])
I get all the Students who are enrolled with either course 1 or course 2. I'm interested only in students who are enrolled in both courses.
The below code works but I think it's not the best way to accomplish this:
all_students = Student.objects.all()
stud_id = []
for student in all_students:
course_list = list(student.courses.values_list('pk', flat=True))
check = all(item in course_list for item in [1,2])
if check:
stud_id.append(student.id)
studs = Student.objects.filter(id__in=stud_id)
The idea is to not loop over every student to find if they're enrolled to the given set of courses.