0

I have a very simple DRF ListApiView which is using filters.SearchFilter as filter_backend.

But the problem is it is returning an empty list if no data is found on the queryset.

My Code:

serializers.py

class PhoneSerializer(serializers.ModelSerializer):
    brand_name = serializers.CharField(source='brand')

    class Meta:
        model = models.Phone
        fields = '__all__'

views.py

class PhoneApiView(generics.ListAPIView):
    filter_backends = [filters.SearchFilter]
    serializer_class = serializers.PhoneSerializer
    queryset = models.Phone.objects.all()
    search_fields = ['model_name', 'jan_code']

Result for a successful search

[
    {
        "id": 6,
        "brand_name": "Oppo",
        "model_name": "Oppo Reno 5",
        "image": "http://127.0.0.1:8000/media/phone/reno-5-black-2.jpg",
        "colors": "Red, Blue",
        "jan_code": "785621716768184",
        "brand": 6
    }
]

Expected Result if nothing found (Currently returning an empty list [])

    {
        "response": 'No Data Found'
    }

Now, How do I do that? Thanks

1 Answer 1

2

Try to start with the filter_queryset() method and work your way to the get() method.

    def filter_queryset(self, queryset):
        for backend in list(self.filter_backends):
            queryset = backend().filter_queryset(self.request, queryset, self)
        return queryset

    def get_queryset(self):
        return Phone.objects.all()

    def get(self, request):
        filtered_qs = self.filter_queryset(self.get_queryset())

        
        serializer = PhoneSerializer(filtered_qs, data=request.data)
        serializer.is_valid(raise_exception=True)
        if not filtered_qs.exists():
            return Response({'response': 'No Data Found'})
        return Response(serializer.data)
Sign up to request clarification or add additional context in comments.

10 Comments

yes got an error The response content must be rendered before it can be iterated over. when no data found
I have edited my post above. The response is now returned in the get method instead of the filter_queryset() method.
I don't know what I am doing wrong but this time correct search returns some error.
Can you post the error message?
validate() got an unexpected keyword argument 'raise_exception' This is the error message I am getting.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.