[Django]-How to get extra parameters in a Django Rest Framework ViewSet

5👍

Use request.query_params

From the doc

request.query_params is a more correctly named synonym for
request.GET.

For clarity inside your code, we recommend using request.query_params
instead of the Django’s standard request.GET. Doing so will help keep
your codebase more correct and obvious – any HTTP method type may
include query parameters, not just GET requests

example:

class TagsAPIView(APIView):
    def get(self, request):
        search = request.query_params.get('search')
        if search:
            data = get_paginated_data(
                data=TagSerializer(
                    Tag.objects.filter(name__contains=search).annotate(posts_count=Count('posts')).order_by(
                        '-posts_count').exclude(posts__isnull=True), many=True).data,
                page=request.query_params.get('page'),
                limit=request.query_params.get('limit'),
                url=F"/social/tags/?search={search}"
            )
        else:
            data = get_paginated_data(
                data=TagSerializer(
                    Tag.objects.all().annotate(posts_count=Count('posts')).order_by('-posts_count').exclude(
                        posts__isnull=True),
                    many=True).data,
                page=request.query_params.get('page'),
                limit=request.query_params.get('limit'),
                url=F"/social/tags/?"
            )
        return JsonResponse(data)
👤JPG

Leave a comment