Reputation: 2247
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
Upvotes: 0
Views: 883
Reputation: 306
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)
Upvotes: 2