Answer the question
In order to leave comments, you need to log in
How to properly filter a queryset between many-to-many fields using django-filter?
There are three models:
class Car(models.Model):
sub_types = models.ManyToManyField(SubType)
class SubType(models.Model):
types = models.ManyToManyField(Type)
class Type(models.Model):
pass
class CarFilter(django_filters.FilterSet):
type = django_filters.MethodFilter(action='type_filter')
class Meta:
model = Car
fields = ['sub_type', 'type']
def type_filter(self, queryset, value):
sub_types = list(SubType.objects.filter(types__id=value).values_list('id', flat=True))
cars = queryset.filter(sub_types__in=sub_types)
return cars
class CarsList(generics.ListAPIView):
renderer_classes = (renderers.JSONRenderer,)
model = Car
queryset = Car.objects.all()
serializer_class = CarSerializer
filter_backends = (filters.DjangoFilterBackend, )
filter_class = CarFilter
sub_types = list(SubType.objects.filter(types__id=value).values_list('id', flat=True))
cars = queryset.filter(sub_types__in=sub_types)
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question