How can I filter a ManyToMany field with django-filter
I would like to display an input field on a template where you can filter Student to get these results:
- all of the Students that speak English (Student.languages contains 'English')
- all of the Students that speak English and German (Student.languages contains 'English' and 'German')
# models.py
class Student(models.Model):
name = models.CharField(...)
languages = models.ManyToManyField(Language)
class Language(models.Model):
language = models.CharField(...) # English / German / ...
level = models.CharField(...) # B1 / B2 / C1 / ...
#filters.py
import django_filters as filters
from .models import Employee
class EmployeeFilter(filters.FilterSet):
class Meta:
model = Employee
fields = ['name', 'languages']
How should I modify the EmployeeFilter to make it ready to filter the Students according to their spoken languages?
I tried declaring a class variable named languages like so:
class EmployeeFilter(filters.FilterSet):
languages = filters.ModelChoiceFilter(
queryset = Languages.objects.all()
)
class Meta:
model = Employee
fields = ['name', 'languages']
but it did not work, the filter had no effect.
You can filter on the
languagefield of thelanguages:This means that you thus can filter with
Englishorenglishfor example.You could also use
ModelMultipleChoiceFilterfor example:That being said, the modeling looks weird. One would expect that the level is part of the junction table, not the language itself, so:
You thus then add information in the combination of a student with a language what the skill level is.