Search code examples
django-rest-frameworkdjango-rest-viewsetsdrf-queryset

DRF ViewSet - dealing with query params


I want to change a queryset in my ViewSet depending on query parameters. I see that there is a list of tags in query params, but when I try extract them I get just last tag as a string. And I have no idea why and how it should work. Can someone explain it for me, please?

class RecipeViewSet(ModelViewSet):
    pagination_class = PageNumberPagination
    permission_classes = [IsAuthenticatedOrReadOnly, IsAuthorOrReadOnly]

def get_serializer_class(self):
    if self.action in ['list', 'retrieve']:
        return RecipeListSerializer
    return RecipeCreateSerializer

def get_queryset(self):
    queryset = Recipe.objects.all()

    params = self.request.query_params
    tags = params.get("tags")
    print("params:")
    print(params) # <QueryDict: {'page': ['1'], 'limit': ['6'], 'tags': ['breakfast', 'lunch', 'dinner']}>
    print("tags:")
    print(type(tags)) # <class 'str'>
    print(tags) # I get only str - "dinner"
    if tags:
        queryset = Recipe.objects.filter(tags__slug__in=tags).distinct()
    return queryset

Solution

  • For getting lists you need to use getlist. In your case it would look like this:

    params.getlist("tags[]")
    

    This is because you're working with an instance of type QueryDict and not dict. You can find more info here.