How can I stop django REST framework to show all records if query parameter is wrong

If you are using the DjangoFilterBackend, take a look at the strict Non-Meta option.

The strict option controls whether results are returned when an invalid value is specified by the user for any filter field. By default, strict is set to True meaning that an empty queryset is returned if any field contains an invalid value. You can loosen this behavior by setting strict to False which will effectively ignore a filter field if its value is invalid.

The filter:

from django_filters.filterset import FilterSet

class UserFilter(FilterSet):
    strict = True

    class Meta:
        model = User
        fields = ['username']

The settings: (assumes you have installed django-filter)

REST_FRAMEWORK = {
    'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',)
}

Now, if someone does:

http://api.example.com/users/?username=myuser&badfilter=1

...it will return an empty list, as badfilter does not exist.

As the FilterSet automatically defaults to strict=True, I have a feeling that you are not taking advantage of the DjangoFilterBackend.


The marked answer didn't work for me. I solved it by overriding the "get" method:

class UserListCreateView(generics.ListCreateAPIView):
    queryset = User.objects.filter(is_archived=False)
    ordering_fields = ('is_active')
    filter_class = userFilter

    @staticmethod
    def is_valid_query_params(query_params):
        # do validations here
        ...

    def get(self, request, *args, **kwargs):
        if not self.is_valid_query_params(request.query_params):
            return Response([])  # send empty response 
        return super(UserListCreateView, self).get(request, *args, **kwargs)