Can I add a global query parameter to all methods on all Viewset endpoints in Django Rest Framework?

32 Views Asked by At

For some purpose I need to add a query parameter to all DRF API viewset method calls and I need to be able to supply from Swagger. In FastAPI it is easily done with a dependency injection on global level like this:

async def code(code: Code = None):
    """Dependency to add code query parameter to all endpoints"""
    pass


fastapi_app = FastAPI(docs_url=None, title="SAF2 API", dependencies=[Depends(code)])

But I have been struggling with custom filters and middleware in Django, but I am not getting it to work. Filters seem to only apply to GET methods and I don't know a lot about middleware to write one myself. I can put it manually on all endpoints with decorators and stuff but that is all very ugly. My viewset looks like this:

class CustomerViewSet(viewsets.ModelViewSet):
    authentication_classes = [SessionAuthentication, BasicAuthentication]
    permission_classes = [IsAuthenticated]
    serializer_class = CustomerSerializer
    queryset = Customer.objects.all()

    filter_backends = [
        filters.SearchFilter,
        filters.OrderingFilter,
        django_filters.rest_framework.DjangoFilterBackend,
    ]
    search_fields = ["full_name", "name", "status"]
    filterset_fields = ["full_name", "name", "status"]

Any help or reference to documentation would be appreciated greatly!

A nice bonus would be to add custom headers to all requests.

0

There are 0 best solutions below