django - Search filter not working in Rest framework
问题描述
A search filter was working fine in this and there's a need to filter out the list with a user-defined distance and for that, a get function is written. Now, the filter is gone. It is appearing when I comment out the get functions.
class ServiceProviderList(generics.ListAPIView):
queryset = ProfileCompletion.objects.all()
serializer_class=ProfilecompletioneSerializer
filterset_class=SnippetFilter
filter_backends = [DjangoFilterBackend,SearchFilter]
filterset_fields = ['fullname', 'category','departments','services']
search_fields = ['fullname', 'category__name','departments__dept_name','services__service_name']
def get(self,request,*args, **kwargs):
pk=self.kwargs.get('pk')
customer = CustomerProfile.objects.get(user=pk)
Dist = request.GET.get("distance")
rad=float(Dist)
radius=rad/111
print(radius)
query = ProfileCompletion.objects.filter(location__distance_lte=(customer.location,radius))
serializer = ProfilecompletioneSerializer(query,many=True)
data = serializer.data
return Response({"message":"Listed Successfully.","data":data})
解决方案
You are lossing all the functionalities because you are overriding the wrong method. Instead of get()
method, you should override get_queryset
method:
class ServiceProviderList(generics.ListAPIView):
queryset = ProfileCompletion.objects.all()
serializer_class=ProfilecompletioneSerializer
filterset_class=SnippetFilter
filter_backends = [DjangoFilterBackend,SearchFilter]
filterset_fields = ['fullname', 'category','departments','services']
search_fields = ['fullname', 'category__name','departments__dept_name','services__service_name']
def get_queryset(self,*args, **kwargs):
qset = super().get_queryset(*args, **kwargs)
pk=self.kwargs.get('pk')
customer = CustomerProfile.objects.get(user=pk)
dist = self.request.GET.get("distance")
rad=float(dist)
radius=rad/111
return qset.filter(location__distance_lte=(customer.location,radius))