whoisearth
whoisearth

Reputation: 4170

Django Rest Framework - Return no values if filter is not selected

I have a fairly simple view where, if no filters are selected, I want the api call to return nothing. Currently the base api url returns everything and the filters successfully limit the return which is half way to what I want.

so this would return values:

http://localhost:8000/api/v1/widgets/?name=abc&list=def

this would return no results:

http://localhost:8000/api/v1/widgets/

Here is my current view:

class WidgetViewSet(EncryptedLookupGenericViewSet,
                      viewsets.ModelViewSet,
                      ):
    queryset = Widget.objects.all()
    serializer_class = WidgetSerializer
    permission_classes=[IsAuthenticated, ]
    lookup_field = 'id'
    filter_class = WidgetFilter

    def get_queryset(self):
        return super(WidgetViewSet, self).get_queryset().filter(list__owner=self.request.user)

Upvotes: 1

Views: 852

Answers (1)

Sardorbek Imomaliev
Sardorbek Imomaliev

Reputation: 15400

You can just check if request.GET is empty

def get_queryset(self):
    if self.request.GET:
        return super(WidgetViewSet, self).get_queryset().filter(list__owner=self.request.user)
    else:
        return self.queryset.none()

Upvotes: 1

Related Questions