Search code examples
djangodjango-orm

Django - Filter on ManyToManyField


I have two models:

class Student(models.Model):
    first_name = models.CharField()
    last_name = models.CharField()


class Group(models.Model):
    name = models.CharField()
    students = models.ManyToManyField(Student)

Some data (first_name and last_name concatenated):

Group #1 | Blak Coleman
Group #1 | Miguel Scott
Group #2 | Jordan Barnes
Group #2 | Jordan Gustman
Group #2 | Jekson Barnes
Group #3 | Jordan Smith

As you can see theres three students by name Jordan. So I need to return groups which in students queryset has only students by name Jordan.

I tried this:

groups = Group.objects.filter(students__first_name='Jordan')

But group.first().students.all() contains all the students not only Jordan. Expected result:

Group #2 | Jordan Barnes
Group #2 | Jordan Gustman
Group #3 | Jordan Smith

How could I do this?


Solution

  • This worked:

    from django.db.models import Prefetch
    
    students = Student.objects.filter(first_name='Jordan')
    prefetch = Prefetch('students', queryset=students)
    groups = Group.objects.prefetch_related(prefetch)
    groups = [group for group in groups if len(group.students.all())]