[Answered ]-Django Many To Many table filter makes too many sql queries

1👍

This has nothing to do with filtering, but with serializing: your serializer forces to fetch the related Branches for each Department individually, you can fetch these all in one extra query with:

class DepartmentListAPIView(generics.ListAPIView):
    queryset = Department.objects.prefetch_related('branch')
    serializer_class = DepartmentSerializer
    filter_backends = (filters.DjangoFilterBackend,)
    filterset_class = DepartmentFilter

Note: Since a ManyToManyField refers to a collection of elements,
ManyToManyFields are normally given a plural name. You thus might want
to consider renaming branch to branches.

Leave a comment