Home > database >  How to return empty queryset from django_filters.FilterSet in API view if querystring hasn't an
How to return empty queryset from django_filters.FilterSet in API view if querystring hasn't an

Time:12-19

I use django-filter package with djangorestframework package for filter objects that return from API view. There are my files:

# models.py
class Symbol(models.Model):
    title = models.CharField(max_length=30, verbose_name='title')
    

# serializers.py
class SymbolSerializer(serializers.ModelSerializer):
    class Meta:
        model = Symbol
        fields = ('title',)

    
# filters.py
class SymbolFilter(django_filters.FilterSet):
    st = django_filters.CharFilter(method='get_st', label='search')

    def get_st(self, queryset, field_name, value):
        return queryset.filter(title__icontains=value)

    class Meta:
        model = Symbol


# views.py 
@api_view(['GET'])
def symbol_list(request):
    queryset = Symbol.objects.all()
    view_filter = APIFilters.APISymbolFilter(request.GET, queryset=queryset)
    if (view_filter.is_valid() is False) or (not view_filter.qs):
        return Response(None, status=status.HTTP_404_NOT_FOUND)

    ser = SymbolSerializer(view_filter.qs, many=True)
    return Response(ser.data, status=status.HTTP_200_OK)


# urls.py 
from .views import * 
urlpatterns = [
    path('symbol/list/', symbol_list, name='symbol_list'),
]   

So, If I sent get request to localhost:8000/symbol/list/?st=sometitle all things are good and I will got Symbol objects that have sometitle in there title field. But when I remove st from querystring, django-filter will return all objects in Symbol model. My question is:

How Can I return empty queryset if st key isn't in querystring or if filter(title__icontains=value) was empty?

CodePudding user response:

I am assuming by default meaning if st query param isnt set u want to return an empty list. If that's the case u can this.


@api_view(['GET'])
def symbol_list(request):
    # check if st is set
    if request.GET.get("st", None):
       queryset = Symbol.objects.all()
    else:
       queryset = Symbol.objects.none()
    view_filter = APIFilters.APISymbolFilter(request.GET, queryset=queryset)
    if (view_filter.is_valid() is False) or (not view_filter.qs):
        return Response(None, status=status.HTTP_404_NOT_FOUND)

    ser = SymbolSerializer(view_filter.qs, many=True)
    return Response(ser.data, status=status.HTTP_200_OK)

  • Related